3.7.6.1 Relationship Types
The four association types in CakePHP are: hasOne, hasMany, belongsTo, and hasAndBelongsToMany (HABTM).
| Relationship | Association Type | Example |
|---|---|---|
| one to one | hasOne | A user has one profile. |
| one to many | hasMany | Users in a system can have multiple recipes. |
| one to many | belongsTo | A recipe belongs to a user. |
| many to many | hasAndBelongsToMany | Recipes have, and belong to many tags. |
Associations are defined by creating a class variable named after the association you are defining. The class variable can sometimes be as simple as a string, but can be as complete as a multidimensional array used to define association specifics.
<?php
class User extends AppModel {
var $name = 'User';
var $hasOne = 'Profile';
var $hasMany = array(
'Recipe' => array(
'className' => 'Recipe',
'conditions' => 'Recipe.approved = 1',
'order' => 'Recipe.created DESC'
)
);
}
?>
<?phpclass User extends AppModel {var $name = 'User';var $hasOne = 'Profile';var $hasMany = array('Recipe' => array('className' => 'Recipe','conditions' => 'Recipe.approved = 1','order' => 'Recipe.created DESC'));}?>
In the above example, the first instance of the word 'Recipe' is what is termed an 'Alias'. This is an identifier for the relationship and can be anything you choose. Usually, you will choose the same name as the class that it references. However, aliases must be unique both within a single model and on both sides of a belongsTo/hasMany or a belongTo/hasOne relationship. Choosing non-unique names for model aliases can cause unexpected behavior.
