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 | A user can have multiple recipes. |
| many to one | belongsTo | Many recipes belong 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' => array('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' => array('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 belongsTo/hasOne relationship. Choosing non-unique names for model aliases can cause unexpected behavior.
Cake will automatically create links between associated model objects. So for example in your User model you can access the Recipe model as
$this->Recipe->someFunction();
$this->Recipe->someFunction();
Similarly in your controller you can access an associated model simply by following your model associations and without adding it to the $uses array:
$this->User->Recipe->someFunction();
$this->User->Recipe->someFunction();
Remember that associations are defined 'one way'. If you define User hasMany Recipe that has no effect on the Recipe Model. You need to define Recipe belongsTo User to be able to access the User model from your Recipe model
