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'
        )
    );
}

?>
  1. <?php
  2. class User extends AppModel {
  3. var $name = 'User';
  4. var $hasOne = 'Profile';
  5. var $hasMany = array(
  6. 'Recipe' => array(
  7. 'className' => 'Recipe',
  8. 'conditions' => array('Recipe.approved' => '1'),
  9. 'order' => 'Recipe.created DESC'
  10. )
  11. );
  12. }
  13. ?>

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();
  1. $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();
  1. $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