Welcome to the Cookbook

loading...

3.7.6 Associations: Linking Models Together

There is no translation yet for this section. Please help out and translate this.. More information about translations

One of the most powerful features of CakePHP is the ability to link relational mapping provided by the model. In CakePHP, the links between models are handled through associations.

Defining relations between different objects in your application should be a natural process. For example: in a recipe database, a recipe may have many reviews, reviews have a single author, and authors may have many recipes. Defining the way these relations work allows you to access your data in an intuitive and powerful way.

The purpose of this section is to show you how to plan for, define, and utilize associations between models in CakePHP.

While data can come from a variety of sources, the most common form of storage in web applications is a relational database. Most of what this section covers will be in that context.

For information on associations with Plugin models, see Plugin Models.

3.7.6.1 Relationship Types

There is no translation yet for this section. Please help out and translate this.. More information about translations

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

3.7.6.2 hasOne

There is no translation yet for this section. Please help out and translate this.. More information about translations

Let’s set up a User model with a hasOne relationship to a Profile model.

First, your database tables need to be keyed correctly. For a hasOne relationship to work, one table has to contain a foreign key that points to a record in the other. In this case the profiles table will contain a field called user_id. The basic pattern is:

hasOne: the other model contains the foreign key.
Relation Schema
Apple hasOne Banana bananas.apple_id
User hasOne Profile profiles.user_id
Doctor hasOne Mentor mentors.doctor_id

The User model file will be saved in /app/models/user.php. To define the ‘User hasOne Profile’ association, add the $hasOne property to the model class. Remember to have a Profile model in /app/models/profile.php, or the association won’t work.

<?php

class User extends AppModel {
    var $name = 'User';                
    var $hasOne = 'Profile';   
}
?>
  1. <?php
  2. class User extends AppModel {
  3. var $name = 'User';
  4. var $hasOne = 'Profile';
  5. }
  6. ?>

There are two ways to describe this relationship in your model files. The simplest method is to set the $hasOne attribute to a string containing the classname of the associated model, as we’ve done above.

If you need more control, you can define your associations using array syntax. For example, you might want to limit the association to include only certain records.

<?php

class User extends AppModel {
    var $name = 'User';          
    var $hasOne = array(
        'Profile' => array(
            'className'    => 'Profile',
            'conditions'   => array('Profile.published' => '1'),
            'dependent'    => true
        )
    );    
}
?>
  1. <?php
  2. class User extends AppModel {
  3. var $name = 'User';
  4. var $hasOne = array(
  5. 'Profile' => array(
  6. 'className' => 'Profile',
  7. 'conditions' => array('Profile.published' => '1'),
  8. 'dependent' => true
  9. )
  10. );
  11. }
  12. ?>

Possible keys for hasOne association arrays include:

  • className: the classname of the model being associated to the current model. If you’re defining a ‘User hasOne Profile’ relationship, the className key should equal ‘Profile.’
  • foreignKey: the name of the foreign key found in the other model. This is especially handy if you need to define multiple hasOne relationships. The default value for this key is the underscored, singular name of the current model, suffixed with ‘_id’. In the example above it would default to 'user_id'.
  • conditions: An SQL fragment used to filter related model records. It’s good practice to use model names in SQL fragments: “Profile.approved = 1” is always better than just “approved = 1.”
  • fields: A list of fields to be retrieved when the associated model data is fetched. Returns all fields by default.
  • order: An SQL fragment that defines the sorting order for the returned associated rows.
  • dependent: When the dependent key is set to true, and the model’s delete() method is called with the cascade parameter set to true, associated model records are also deleted. In this case we set it true so that deleting a User will also delete her associated Profile.

Once this association has been defined, find operations on the User model will also fetch a related Profile record if it exists:

//Sample results from a $this->User->find() call.

Array
(
    [User] => Array
        (
            [id] => 121
            [name] => Gwoo the Kungwoo
            [created] => 2007-05-01 10:31:01
        )
    [Profile] => Array
        (
            [id] => 12
            [user_id] => 121
            [skill] => Baking Cakes
            [created] => 2007-05-01 10:31:01
        )
)

3.7.6.3 belongsTo

There is no translation yet for this section. Please help out and translate this.. More information about translations

Now that we have Profile data access from the User model, let’s define a belongsTo association in the Profile model in order to get access to related User data. The belongsTo association is a natural complement to the hasOne and hasMany associations: it allows us to see the data from the other direction.

When keying your database tables for a belongsTo relationship, follow this convention:

belongsTo: the current model contains the foreign key.
Relation Schema
Banana belongsTo Apple bananas.apple_id
Profile belongsTo User profiles.user_id
Mentor belongsTo Doctor mentors.doctor_id

If a model(table) contains a foreign key, it belongsTo the other model(table).

We can define the belongsTo association in our Profile model at /app/models/profile.php using the string syntax as follows:

<?php

class Profile extends AppModel {
    var $name = 'Profile';                
    var $belongsTo = 'User';   
}
?>
  1. <?php
  2. class Profile extends AppModel {
  3. var $name = 'Profile';
  4. var $belongsTo = 'User';
  5. }
  6. ?>

We can also define a more specific relationship using array syntax:

<?php

class Profile extends AppModel {
    var $name = 'Profile';                
    var $belongsTo = array(
        'User' => array(
            'className'    => 'User',
            'foreignKey'    => 'user_id'
        )
    );  
}
?>
  1. <?php
  2. class Profile extends AppModel {
  3. var $name = 'Profile';
  4. var $belongsTo = array(
  5. 'User' => array(
  6. 'className' => 'User',
  7. 'foreignKey' => 'user_id'
  8. )
  9. );
  10. }
  11. ?>

Possible keys for belongsTo association arrays include:

  • className: the classname of the model being associated to the current model. If you’re defining a ‘Profile belongsTo User’ relationship, the className key should equal ‘User.’
  • foreignKey: the name of the foreign key found in the current model. This is especially handy if you need to define multiple belongsTo relationships. The default value for this key is the underscored, singular name of the other model, suffixed with ‘_id’.
  • conditions: An SQL fragment used to filter related model records. It’s good practice to use model names in SQL fragments: “User.active = 1” is always better than just “active = 1.”
  • fields: A list of fields to be retrieved when the associated model data is fetched. Returns all fields by default.
  • order: An SQL fragment that defines the sorting order for the returned associated rows.
  • counterCache: If set to true the associated Model will automatically increase or decrease the “[singular_model_name]_count” field in the foreign table whenever you do a save() or delete(). If its a string then its the field name to use. The value in the counter field represents the number of related rows.
  • counterScope: Optional conditions array to use for updating counter cache field.

Once this association has been defined, find operations on the Profile model will also fetch a related User record if it exists:

//Sample results from a $this->Profile->find() call.

Array
(
   [Profile] => Array
        (
            [id] => 12
            [user_id] => 121
            [skill] => Baking Cakes
            [created] => 2007-05-01 10:31:01
        )    
    [User] => Array
        (
            [id] => 121
            [name] => Gwoo the Kungwoo
            [created] => 2007-05-01 10:31:01
        )
)

3.7.6.4 hasMany

There is no translation yet for this section. Please help out and translate this.. More information about translations

Next step: defining a “User hasMany Comment” association. A hasMany association will allow us to fetch a user’s comments when we fetch a User record.

When keying your database tables for a hasMany relationship, follow this convention:

hasMany: the other model contains the foreign key.
Relation Schema
User hasMany Comment Comment.user_id
Cake hasMany Virtue Virtue.cake_id
Product hasMany Option Option.product_id

We can define the hasMany association in our User model at /app/models/user.php using the string syntax as follows:

<?php

class User extends AppModel {
    var $name = 'User';                
    var $hasMany = 'Comment';   
}
?>
  1. <?php
  2. class User extends AppModel {
  3. var $name = 'User';
  4. var $hasMany = 'Comment';
  5. }
  6. ?>

We can also define a more specific relationship using array syntax:

<?php

class User extends AppModel {
    var $name = 'User';                
    var $hasMany = array(
        'Comment' => array(
            'className'     => 'Comment',
            'foreignKey'    => 'user_id',
            'conditions'    => array('Comment.status' => '1'),
            'order'    => 'Comment.created DESC',
            'limit'        => '5',
            'dependent'=> true
        )
    );  
}
?>
  1. <?php
  2. class User extends AppModel {
  3. var $name = 'User';
  4. var $hasMany = array(
  5. 'Comment' => array(
  6. 'className' => 'Comment',
  7. 'foreignKey' => 'user_id',
  8. 'conditions' => array('Comment.status' => '1'),
  9. 'order' => 'Comment.created DESC',
  10. 'limit' => '5',
  11. 'dependent'=> true
  12. )
  13. );
  14. }
  15. ?>

Possible keys for hasMany association arrays include:

  • className: the classname of the model being associated to the current model. If you’re defining a ‘User hasMany Comment’ relationship, the className key should equal ‘Comment.’
  • foreignKey: the name of the foreign key found in the other model. This is especially handy if you need to define multiple hasMany relationships. The default value for this key is the underscored, singular name of the actual model, suffixed with ‘_id’.
  • conditions: An SQL fragment used to filter related model records. It’s good practice to use model names in SQL fragments: “Comment.status = 1” is always better than just “status = 1.”
  • fields: A list of fields to be retrieved when the associated model data is fetched. Returns all fields by default.
  • order: An SQL fragment that defines the sorting order for the returned associated rows.
  • limit: The maximum number of associated rows you want returned.
  • offset: The number of associated rows to skip over (given the current conditions and order) before fetching and associating.
  • dependent: When dependent is set to true, recursive model deletion is possible. In this example, Comment records will be deleted when their associated User record has been deleted.
  • exclusive: When exclusive is set to true, recursive model deletion does the delete with a deleteAll() call, instead of deleting each entity separately. This greatly improves performance, but may not be ideal for all circumstances.
  • finderQuery: A complete SQL query CakePHP can use to fetch associated model records. This should be used in situations that require very custom results.

    If a query you're building requires a reference to the associated model ID, use the special {$__cakeID__$} marker in the query. For example, if your Apple model hasMany Orange, the query should look something like this:

    SELECT Orange.* from oranges as Orange WHERE Orange.apple_id IN ({$__cakeID__$});
    
    1. SELECT Orange.* from oranges as Orange WHERE Orange.apple_id IN ({$__cakeID__$});
    Remember to use IN ({$__cakeID__$}) for hasMany and hasAndBelongsToMany associations as Cake will replace {$__cakeID__$} with a list of ids for these types of associations.

Once this association has been defined, find operations on the User model will also fetch related Comment records if they exist:

//Sample results from a $this->User->find() call.

Array
(  
    [User] => Array
        (
            [id] => 121
            [name] => Gwoo the Kungwoo
            [created] => 2007-05-01 10:31:01
        )
    [Comment] => Array
        (
            [0] => Array
                (
                    [id] => 123
                    [user_id] => 121
                    [title] => On Gwoo the Kungwoo
                    [body] => The Kungwooness is not so Gwooish
                    [created] => 2006-05-01 10:31:01
                )
            [1] => Array
                (
                    [id] => 124
                    [user_id] => 121
                    [title] => More on Gwoo
                    [body] => But what of the ‘Nut?
                    [created] => 2006-05-01 10:41:01
                )
        )
)

One thing to remember is that you’ll need a complimentary Comment belongsTo User association in order to get the data from both directions. What we’ve outlined in this section empowers you to get Comment data from the User. Adding the Comment belongsTo User association in the Comment model empowers you to get User data from the Comment model - completing the connection and allowing the flow of information from either model’s perspective.

3.7.6.5 hasAndBelongsToMany (HABTM)

The original text for this section has changed since it was translated. Please help resolve this difference. You can:

More information about translations

V pořádku. V tomto místě se již můžete nazývat profesionál ve vazbách modelů. Máte zkušenosti ve třech typech vazeb, které vyjadřují množství objektových vztahů.

Pojďme se pustit do posledního typu vazby: hasAndBelongsToMany nebo též HABTM. Tento typ vazby se používá, pokud potřebujete spojit 2 modely opakovaně vícekrát různými cestami.

Hlavním rozdílem mezi vazbami typu hasMany a HABTM je, že vazba mezi modely v HABTM není jedinečná (exklusivní). Například, chceme spojit "Recept" (Recipe) s popiskem (Tag) pomocí HABTM. Připojení popisku "Italské" k receptu mojí babičky na Gnochi není jedinečné. Popisek "Italské" můžu připojit i ke špagetám pokud chci.

Vazba mezi objekty pomocí hasMany je jedinečná. Pokud uživatel má mnoho komentářů, pak každý komentář je připojen pouze k tomuto jednomu uživateli.

Pojďme dále. Budeme potřebovat vytvořit extra tabulku v databázi pro uložení HABTM vazby. Jméno nové tabulky musí obsahovat jména obou modelů oddělených podtržítkem. Obsahem tabulky jsou nejméně 2 sloupečky, které odkazují jako cizí klíče do vazebních tabulek. Vyhněte se problému - nedefinujte primární klíč na těchto dvou sloupcích, využijte index unikátní. Pokud plánujete přidat další informace do této tabulky, pak je dobrý nápadem přidat sloupeček s primárním id pro snadnější práci s ostatními modely

HABTM vyžaduje oddělenou spojovací tabulku, která obsahuje jména obou modelů.

Vazba Schéma
Recipe HABTM Tag id, recipes_tags.recipe_id, recipes_tags.tag_id
Cake HABTM Fan id, cakes_fans.cake_id, cakes_fans.fan_id
Foo HABTM Bar id, bars_foos.foo_id, bars_foos.bar_id

Název tabulky je dle konvence v alfabetickém pořadí.

Zatímco jsme vytvořili novou tabulku, můžeme definovat HABTM vazbu v modelech. Pojďme rovnou na syntaxi:

<?php

class Recipe extends AppModel {
    var $name = 'Recipe';   
    var $hasAndBelongsToMany = array(
        'Tag' =>
            array(
                 'className'              => 'Tag',
                 'joinTable'              => 'recipes_tags',
                 'with'                   => '',
                'foreignKey'             => 'recipe_id',
                'associationForeignKey'  => 'tag_id',
                'unique'                 => true,
                'conditions'             => '',
                'fields'                 => '',
                'order'                  => '',
                'limit'                  => '',
                'offset'                 => '',
                'finderQuery'            => '',
                'deleteQuery'            => '',
                'insertQuery'            => ''
            )
    );
}
?>
  1. <?php
  2. class Recipe extends AppModel {
  3. var $name = 'Recipe';
  4. var $hasAndBelongsToMany = array(
  5. 'Tag' =>
  6. array(
  7. 'className' => 'Tag',
  8. 'joinTable' => 'recipes_tags',
  9. 'with' => '',
  10. 'foreignKey' => 'recipe_id',
  11. 'associationForeignKey' => 'tag_id',
  12. 'unique' => true,
  13. 'conditions' => '',
  14. 'fields' => '',
  15. 'order' => '',
  16. 'limit' => '',
  17. 'offset' => '',
  18. 'finderQuery' => '',
  19. 'deleteQuery' => '',
  20. 'insertQuery' => ''
  21. )
  22. );
  23. }
  24. ?>

Povolené klíče pro HABTM vazbu:

  • className: název třídy modelu připojeného k aktuálnímu modelu. Pokud definujete vazbu ‘User hasMany Comment', název třídy je ‘Comment.'
  • joinTable: název spojovací tabulku pužité ve vazbě (pokud název neodpovídá konvencím).
  • with: definuje název modelu pro spojovací tabulku. Defaultně CakePHP vytvoří tento model pro Tebe automaticky. Pro příklad výše se nazývá RecipesTag. Použitím tohoto klíče můžete přepsat defaultní název.
  • foreignKey: název cizího klíče v tomto modelu. Toto je speciálně užitečné, pokud defnujete rozmanité HABTM vazby. Defaultní hodnotou pro tento klíč je jednotné číslo tohoto modelu s příponou ‘_id'.
  • associationForeignKey:název cizího klíče ve vazebním modelu. Toto je speciálně užitečné, pokud defnujete rozmanité HABTM vazby. Defaultní hodnotou pro tento klíč je jednotné číslo vazebního modelu s příponou ‘_id'.
  • unique: If true (default value) cake will first delete existing relationship records in the foreign keys table before inserting new ones, when updating a record. So existing associations need to be passed again when updating.
  • conditions: SQL fragment použitý pro filtrování záznamů. Je dobrým zvykem psát i názvy modelů: "Comment.status = 1" namísto pouhého "status = 1."
  • fields: seznam sloupců, které budou vráceny. Defaultně jsou vráceny sloupečky všechny.
  • order: SQL fragment který definuje třídění
  • limit: počet řádků, který je maximálně příkazem vrácen
  • offset: počet řádků, které jsou "přeskočeny", než začne příkaz řádky vracet
  • finderQuery, deleteQuery, insertQuery: kompletní SQL dotaz, který je použit pro načítání, mazání nebo vytvoření nového záznamu. Toto můžu využít v situacích, kdy vyžaduji velice uživatelský výsledek.

Když je tato vazba definovaná, vyhledávací operace na model receptů bude také vracet řádky popisků, pokud existují:

//Sample results from a $this->Recipe->find() call.

Array
(  
    [Recipe] => Array
        (
            [id] => 2745
            [name] => Chocolate Frosted Sugar Bombs
            [created] => 2007-05-01 10:31:01
            [user_id] => 2346
        )
    [Tag] => Array
        (
            [0] => Array
                (
                    [id] => 123
                    [name] => Breakfast
                )
           [1] => Array
                (
                    [id] => 124
                    [name] => Dessert
                )
           [2] => Array
                (
                    [id] => 125
                    [name] => Heart Disease
                )
        )
)

Nezapomeňte definovat vazbu HABTM i pro popisky(Tag), pokud bude chtít získat záznamy o receptech v případě použití modelu popisků (Tag).

It is also possible to execute custom find queries based on HABTM relationships. Consider the following examples:

Assuming the same structure in the above example (Recipe HABTM Tag), let's say we want to fetch all Recipes with the tag 'Dessert', one potential (wrong) way to achieve this would be to apply a condition to the association itself:

$this->Recipe->bindModel(array(
	'hasAndBelongsToMany' => array(
		'Tag' => array('conditions'=>array('Tag.name'=>'Dessert'))
)));
$this->Recipe->find('all');
  1. $this->Recipe->bindModel(array(
  2. 'hasAndBelongsToMany' => array(
  3. 'Tag' => array('conditions'=>array('Tag.name'=>'Dessert'))
  4. )));
  5. $this->Recipe->find('all');
//Data Returned
Array
(  
    0 => Array
        {
        [Recipe] => Array
            (
                [id] => 2745
                [name] => Chocolate Frosted Sugar Bombs
                [created] => 2007-05-01 10:31:01
                [user_id] => 2346
            )
        [Tag] => Array
            (
               [0] => Array
                    (
                        [id] => 124
                        [name] => Dessert
                    )
            )
    )
    1 => Array
        {
        [Recipe] => Array
            (
                [id] => 2745
                [name] => Crab Cakes
                [created] => 2008-05-01 10:31:01
                [user_id] => 2349
            )
        [Tag] => Array
            (
            }
        }
}

Notice that this example returns ALL recipes but only the "Dessert" tags. To properly achieve our goal, there are a number of ways to do it. One option is to search the Tag model (instead of Recipe), which will also give us all of the associated Recipes.

$this->Recipe->Tag->find('all', array('conditions'=>array('Tag.name'=>'Dessert')));
  1. $this->Recipe->Tag->find('all', array('conditions'=>array('Tag.name'=>'Dessert')));

We could also use the join table model (which CakePHP provides for us), to search for a given ID.

$this->Recipe->bindModel(array('hasOne' => array('RecipesTag')));
$this->Recipe->find('all', array(
		'fields' => array('Recipe.*'),
		'conditions'=>array('RecipesTag.tag_id'=>124) // id of Dessert
));
  1. $this->Recipe->bindModel(array('hasOne' => array('RecipesTag')));
  2. $this->Recipe->find('all', array(
  3. 'fields' => array('Recipe.*'),
  4. 'conditions'=>array('RecipesTag.tag_id'=>124) // id of Dessert
  5. ));

It's also possible to create an exotic association for the purpose of creating as many joins as necessary to allow filtering, for example:

$this->Recipe->bindModel(array(
	'hasOne' => array(
		'RecipesTag',
		'FilterTag' => array(
			'className' => 'Tag',
			'foreignKey' => false,
			'conditions' => array('FilterTag.id = RecipesTag.id')
))));
$this->Recipe->find('all', array(
		'fields' => array('Recipe.*'),
		'conditions'=>array('FilterTag.name'=>'Dessert')
));
  1. $this->Recipe->bindModel(array(
  2. 'hasOne' => array(
  3. 'RecipesTag',
  4. 'FilterTag' => array(
  5. 'className' => 'Tag',
  6. 'foreignKey' => false,
  7. 'conditions' => array('FilterTag.id = RecipesTag.id')
  8. ))));
  9. $this->Recipe->find('all', array(
  10. 'fields' => array('Recipe.*'),
  11. 'conditions'=>array('FilterTag.name'=>'Dessert')
  12. ));

Both of which will return the following data:

//Data Returned
Array
(  
    0 => Array
        {
        [Recipe] => Array
            (
                [id] => 2745
                [name] => Chocolate Frosted Sugar Bombs
                [created] => 2007-05-01 10:31:01
                [user_id] => 2346
            )
    [Tag] => Array
        (
            [0] => Array
                (
                    [id] => 123
                    [name] => Breakfast
                )
           [1] => Array
                (
                    [id] => 124
                    [name] => Dessert
                )
           [2] => Array
                (
                    [id] => 125
                    [name] => Heart Disease
                )
        )
}

For more information on binding model associations on the fly see Creating and destroying associations on the fly

Mix and match techniques to achieve your specific objective.

3.7.6.6 Creating and Destroying Associations on the Fly

There is no translation yet for this section. Please help out and translate this.. More information about translations

Sometimes it becomes necessary to create and destroy model associations on the fly. This may be for any number of reasons:

  • You want to reduce the amount of associated data fetched, but all your associations are on the first level of recursion.
  • You want to change the way an association is defined in order to sort or filter associated data.

This association creation and destruction is done using the CakePHP model bindModel() and unbindModel() methods. (There is also a very helpful behavior called "Containable", please refer to manual section about Built-in behaviors for more information). Let's set up a few models so we can see how bindModel() and unbindModel() work. We'll start with two models:

<?php

class Leader extends AppModel {
    var $name = 'Leader';
 
    var $hasMany = array(
        'Follower' => array(
            'className' => 'Follower',
            'order'     => 'Follower.rank'
        )
    );
}

?>

<?php

class Follower extends AppModel {
    var $name = 'Follower';
}

?>
  1. <?php
  2. class Leader extends AppModel {
  3. var $name = 'Leader';
  4. var $hasMany = array(
  5. 'Follower' => array(
  6. 'className' => 'Follower',
  7. 'order' => 'Follower.rank'
  8. )
  9. );
  10. }
  11. ?>
  12.  
  13. <?php
  14. class Follower extends AppModel {
  15. var $name = 'Follower';
  16. }
  17. ?>

Now, in the LeadersController, we can use the find() method in the Leader model to fetch a Leader and its associated followers. As you can see above, the association array in the Leader model defines a "Leader hasMany Followers" relationship. For demonstration purposes, let's use unbindModel() to remove that association in a controller action.

function someAction() {
    // This fetches Leaders, and their associated Followers
    $this->Leader->find('all');
  
    // Let's remove the hasMany...
    $this->Leader->unbindModel(
        array('hasMany' => array('Follower'))
    );
  
    // Now using a find function will return 
    // Leaders, with no Followers
    $this->Leader->find('all');
  
    // NOTE: unbindModel only affects the very next 
    // find function. An additional find call will use 
    // the configured association information.
  
    // We've already used find('all') after unbindModel(), 
    // so this will fetch Leaders with associated 
    // Followers once again...
    $this->Leader->find('all');
}
  1. function someAction() {
  2. // This fetches Leaders, and their associated Followers
  3. $this->Leader->find('all');
  4. // Let's remove the hasMany...
  5. $this->Leader->unbindModel(
  6. array('hasMany' => array('Follower'))
  7. );
  8. // Now using a find function will return
  9. // Leaders, with no Followers
  10. $this->Leader->find('all');
  11. // NOTE: unbindModel only affects the very next
  12. // find function. An additional find call will use
  13. // the configured association information.
  14. // We've already used find('all') after unbindModel(),
  15. // so this will fetch Leaders with associated
  16. // Followers once again...
  17. $this->Leader->find('all');
  18. }

Removing or adding associations using bind- and unbindModel() only works for the next model operation only unless the second parameter has been set to false. If the second parameter has been set to false, the bind remains in place for the remainder of the request.

Here’s the basic usage pattern for unbindModel():

$this->Model->unbindModel(
    array('associationType' => array('associatedModelClassName'))
);
  1. $this->Model->unbindModel(
  2. array('associationType' => array('associatedModelClassName'))
  3. );

Now that we've successfully removed an association on the fly, let's add one. Our as-of-yet unprincipled Leader needs some associated Principles. The model file for our Principle model is bare, except for the var $name statement. Let's associate some Principles to our Leader on the fly (but remember–only for just the following find operation). This function appears in the LeadersController:

function anotherAction() {
    // There is no Leader hasMany Principles in 
    // the leader.php model file, so a find here, 
    // only fetches Leaders.
    $this->Leader->find('all');
 
    // Let's use bindModel() to add a new association 
    // to the Leader model:
    $this->Leader->bindModel(
        array('hasMany' => array(
                'Principle' => array(
                    'className' => 'Principle'
                )
            )
        )
    );
 
    // Now that we're associated correctly, 
    // we can use a single find function to fetch 
    // Leaders with their associated principles:
    $this->Leader->find('all');
}
  1. function anotherAction() {
  2. // There is no Leader hasMany Principles in
  3. // the leader.php model file, so a find here,
  4. // only fetches Leaders.
  5. $this->Leader->find('all');
  6. // Let's use bindModel() to add a new association
  7. // to the Leader model:
  8. $this->Leader->bindModel(
  9. array('hasMany' => array(
  10. 'Principle' => array(
  11. 'className' => 'Principle'
  12. )
  13. )
  14. )
  15. );
  16. // Now that we're associated correctly,
  17. // we can use a single find function to fetch
  18. // Leaders with their associated principles:
  19. $this->Leader->find('all');
  20. }

There you have it. The basic usage for bindModel() is the encapsulation of a normal association array inside an array whose key is named after the type of association you are trying to create:

$this->Model->bindModel(
        array('associationName' => array(
                'associatedModelClassName' => array(
                    // normal association keys go here...
                )
            )
        )
    );
  1. $this->Model->bindModel(
  2. array('associationName' => array(
  3. 'associatedModelClassName' => array(
  4. // normal association keys go here...
  5. )
  6. )
  7. )
  8. );

Even though the newly bound model doesn't need any sort of association definition in its model file, it will still need to be correctly keyed in order for the new association to work properly.

3.7.6.7 Multiple relations to the same model

There is no translation yet for this section. Please help out and translate this.. More information about translations

There are cases where a Model has more than one relation to another Model. For example you might have a Message model that has two relations to the User model. One relation to the user that sends a message, and a second to the user that receives the message. The messages table will have a field user_id, but also a field recipient_id. Now your Message model can look something like:

<?php
class Message extends AppModel {
    var $name = 'Message';
    var $belongsTo = array(
        'Sender' => array(
            'className' => 'User',
            'foreignKey' => 'user_id'
        ),
        'Recipient' => array(
            'className' => 'User',
            'foreignKey' => 'recipient_id'
        )
    );
}
?>
  1. <?php
  2. class Message extends AppModel {
  3. var $name = 'Message';
  4. var $belongsTo = array(
  5. 'Sender' => array(
  6. 'className' => 'User',
  7. 'foreignKey' => 'user_id'
  8. ),
  9. 'Recipient' => array(
  10. 'className' => 'User',
  11. 'foreignKey' => 'recipient_id'
  12. )
  13. );
  14. }
  15. ?>

Recipient is an alias for the User model. Now let's see what the User model would look like.

<?php
class User extends AppModel {
    var $name = 'User';
    var $hasMany = array(
        'MessageSent' => array(
            'className' => 'Message',
            'foreignKey' => 'user_id'
        ),
        'MessageReceived' => array(
            'className' => 'Message',
            'foreignKey' => 'recipient_id'
        )
    );
}
?>
  1. <?php
  2. class User extends AppModel {
  3. var $name = 'User';
  4. var $hasMany = array(
  5. 'MessageSent' => array(
  6. 'className' => 'Message',
  7. 'foreignKey' => 'user_id'
  8. ),
  9. 'MessageReceived' => array(
  10. 'className' => 'Message',
  11. 'foreignKey' => 'recipient_id'
  12. )
  13. );
  14. }
  15. ?>

3.7.6.8 Joining tables

There is no translation yet for this section. Please help out and translate this.. More information about translations

In SQL you can combine related tables using the JOIN statement. This allows you to perform complex searches across multiples tables (i.e: search posts given several tags).

In CakePHP some associations (belongsTo and hasOne) performs automatic joins to retrieve data, so you can issue queries to retrieve models based on data in the related one.

But this is not the case with hasMany and hasAndBelongsToMany associations. Here is where forcing joins comes to the rescue. You only have to define the necessary joins to combine tables and get the desired results for your query.

To force a join between tables you need to use the "modern" syntax for Model::find(), adding a 'joins' key to the $options array. For example:

$options['joins'] = array(
    array(
        'table' => 'channels',
        'alias' => 'Channel',
        'type' => 'LEFT',
        'conditions' => array(
            'Channel.id = Item.channel_id',
        )
    )
);

$Item->find('all', $options);
  1. $options['joins'] = array(
  2. array(
  3. 'table' => 'channels',
  4. 'alias' => 'Channel',
  5. 'type' => 'LEFT',
  6. 'conditions' => array(
  7. 'Channel.id = Item.channel_id',
  8. )
  9. )
  10. );
  11. $Item->find('all', $options);

Note that the 'join' arrays are not keyed.

In the above example, a model called Item is left joined to the channels table. You can alias the table with the model name, so the retrieved data complies with the CakePHP data structure.

The keys that define the join are the following:

  • table: The table for the join.
  • alias: An alias to the table. The name of the model associated with the table is the best bet.
  • type: The type of join: inner, left or right.
  • conditions: The conditions to perform the join.

With joins, you could add conditions based on related model fields:

$options['joins'] = array(
    array('table' => 'channels',
        'alias' => 'Channel',
        'type' => 'LEFT',
        'conditions' => array(
            'Channel.id = Item.channel_id',
        )
    )
);

$options['conditions'] = array(
	'Channel.private' => 1
);

$pirvateItems = $Item->find('all', $options);
  1. $options['joins'] = array(
  2. array('table' => 'channels',
  3. 'alias' => 'Channel',
  4. 'type' => 'LEFT',
  5. 'conditions' => array(
  6. 'Channel.id = Item.channel_id',
  7. )
  8. )
  9. );
  10. $options['conditions'] = array(
  11. 'Channel.private' => 1
  12. );
  13. $pirvateItems = $Item->find('all', $options);

You could perform several joins as needed in hasBelongsToMany:

Suppose a Book hasAndBelongsToMany Tag association. This relation uses a books_tags table as join table, so you need to join the books table to the books_tags table, and this with the tags table:

$options['joins'] = array(
	array('table' => 'books_tags',
		'alias' => 'BooksTag',
		'type' => 'inner',
		'conditions' => array(
			'Books.id = BooksTag.book_id'
		)
	),
	array('table' => 'tags',
		'alias' => 'Tag',
		'type' => 'inner',
		'conditions' => array(
			'BooksTag.tag_id = Tag.id'
		)
	)
);

$options['conditions'] = array(
	'Tag.tag' => 'Novel'
);

$books = $Book->find('all', $options);
  1. $options['joins'] = array(
  2. array('table' => 'books_tags',
  3. 'alias' => 'BooksTag',
  4. 'type' => 'inner',
  5. 'conditions' => array(
  6. 'Books.id = BooksTag.book_id'
  7. )
  8. ),
  9. array('table' => 'tags',
  10. 'alias' => 'Tag',
  11. 'type' => 'inner',
  12. 'conditions' => array(
  13. 'BooksTag.tag_id = Tag.id'
  14. )
  15. )
  16. );
  17. $options['conditions'] = array(
  18. 'Tag.tag' => 'Novel'
  19. );
  20. $books = $Book->find('all', $options);

Using joins with Containable behavior could lead to some SQL errors (duplicate tables), so you need to use the joins method as an alternative for Containable if your main goal is to perform searches based on related data. Containable is best suited to restricting the amount of related data brought by a find statement.