One of the most powerful features of CakePHP is the relational mapping provided by the model. In CakePHP, the links between tables are handled through associations. Associations are the glue between related logical units.
There are four types of associations in CakePHP:
hasOne
hasMany
belongsTo
hasAndBelongsToMany
When associations between models have been defined, Cake will automagically fetch models related to the model you are working with. For example, if a Post model is related to an Author model using a hasMany association, making a call to $this->Post->findAll() in a controller will fetch Post records, as well as all the Author records they are related to.
To use the association correctly it is best to follow the CakePHP naming conventions (see Appendix "Cake Conventions"). If you use CakePHP's naming conventions, you can use scaffolding to visualize your application data, because scaffolding detects and uses the associations between models. Of course you can always customize model associations to work outside of Cake's naming conventions, but we'll save those tips for later. For now, let's just stick to the conventions. The naming conventions that concern us here are the foreign keys, model names, and table names.
Here's a review of what Cake expects for the names of these different elements: (see Appendix "Cake Conventions" for more information on naming)
Foreign Keys: [singular model name]_id. For example, a foreign key in the "authors" table pointing back to the Post a given Author belongs to would be named "post_id".
Table Names: [plural object name]. Since we'd like to store information about blog posts and their authors, the table names are "posts" and "authors", respectively.
Model Names: [CamelCased, singular form of table name]. The model name for the "posts" table is "Post", and the model name for the "authors" table is "Author".
|
Note |
|---|---|
|
CakePHP's scaffolding expects your associations to be in the same order as your colums. So if I have an Article that belongsTo three other models (Author, Editor, and Publisher), I would need three keys: author_id, editor_id, and publisher_id. Scaffolding would expect your associations in the same order as the keys in the table (e.g. first Author, second Editor, lastly Publisher). |
In order to illustrate how some of these associations work, let's continue using the blog application as an example. Imagine that we're going to create a simple user management system for the blog. I suppose it goes without saying we'll want to keep track of Users, but we'd also like each user to have an associated Profile (User hasOne Profile). Users will also be able to create comments and remain associated to them (User hasMany Comments). Once we have the user system working, we'll move to allowing Posts to be related to Tag objects using the hasAndBelongsToMany relationship (Post hasAndBelongsToMany Tags).
In order to set up this association, we'll assume that you've already created the User and Profile models. To define the hasOne assocation between them, we'll need to add an array to the models to tell Cake how they relate. Here's how that looks like:
Example 6.5. /app/models/user.php hasOne
<?php
class User extends AppModel
{
var $name = 'User';
var $hasOne = array('Profile' =>
array('className' => 'Profile',
'conditions' => '',
'order' => '',
'dependent' => true,
'foreignKey' => 'user_id'
)
);
}
?>
The $hasOne array is what Cake uses to build the association between the User and Profile models. Each key in the array allows you to further configure the association:
className (required): the classname of the model you'd like to associate
For our example, we want to specify the 'Profile' model class name.
conditions: SQL condition fragments that define the relationship
We could use this to tell Cake to only associate a Profile that has a green header, if we wished. To define conditions like this, you'd specify a SQL conditions fragment as the value for this key: "Profile.header_color = 'green'".
order: the ordering of the associated models
If you'd like your associated models in a specific order, set the value for this key using an SQL order predicate: "Profile.name ASC", for example.
dependent: if set to true, the associated model is destroyed when this one is.
For example, if the "Cool Blue" profile is associated to "Bob", and I delete the user "Bob", the profile "Cool Blue" will also be deleted.
foreignKey: the name of the foreign key that points to the associated model.
This is here in case you're working with a database that doesn't follow Cake's naming conventions.
Now, when we execute find() or findAll() calls using the Profile model, we should see our associated User model there as well:
$user = $this->User->read(null, '25');
print_r($user);
//output:
Array
(
[User] => Array
(
[id] => 25
[first_name] => John
[last_name] => Anderson
[username] => psychic
[password] => c4k3roxx
)
[Profile] => Array
(
[id] => 4
[name] => Cool Blue
[header_color] => aquamarine
[user_id] = 25
)
)
Now that a User can see its Profile, we'll need to define an association so Profile can see its User. This is done in Cake using the belongsTo assocation. In the Profile model, we'd do the following:
Example 6.6. /app/models/profile.php belongsTo
<?php
class Profile extends AppModel
{
var $name = 'Profile';
var $belongsTo = array('User' =>
array('className' => 'User',
'conditions' => '',
'order' => '',
'foreignKey' => 'user_id'
)
);
}
?>
The $belongsTo array is what Cake uses to build the association between the User and Profile models. Each key in the array allows you to further configure the association:
className (required): the classname of the model you'd like to associate
For our example, we want to specify the 'User' model class name.
conditions: SQL condition fragments that define the relationship
We could use this to tell Cake to only associate a User that is active. You would do this by setting the value of the key to be "User.active = '1'", or something similar.
order: the ordering of the associated models
If you'd like your associated models in a specific order, set the value for this key using an SQL order predicate: "User.last_name ASC", for example.
foreignKey: the name of the foreign key that points to the associated model.
This is here in case you're working with a database that doesn't follow Cake's naming conventions.
Now, when we execute find() or findAll() calls using the Profile model, we should see our associated User model there as well:
$profile = $this->Profile->read(null, '4');
print_r($profile);
//output:
Array
(
[Profile] => Array
(
[id] => 4
[name] => Cool Blue
[header_color] => aquamarine
[user_id] = 25
)
[User] => Array
(
[id] => 25
[first_name] => John
[last_name] => Anderson
[username] => psychic
[password] => c4k3roxx
)
)
Now that User and Profile models are associated and working properly, let's build our system so that User records are associated to Comment records. This is done in the User model like so:
Example 6.7. /app/models/user.php hasMany
<?php
class User extends AppModel
{
var $name = 'User';
var $hasMany = array('Comment' =>
array('className' => 'Comment',
'conditions' => 'Comment.moderated = 1',
'order' => 'Comment.created DESC',
'limit' => '5',
'foreignKey' => 'user_id',
'dependent' => true,
'exclusive' => false,
'finderQuery' => ''
)
);
// Here's the hasOne relationship we defined earlier...
var $hasOne = array('Profile' =>
array('className' => 'Profile',
'conditions' => '',
'order' => '',
'dependent' => true,
'foreignKey' => 'user_id'
)
);
}
?>
The $hasMany array is what Cake uses to build the association between the User and Comment models. Each key in the array allows you to further configure the association:
className (required): the classname of the model you'd like to associate
For our example, we want to specify the 'Comment' model class name.
conditions: SQL condition fragments that define the relationship
We could use this to tell Cake to only associate a Comment that has been moderated. You would do this by setting the value of the key to be "Comment.moderated = 1", or something similar.
order: the ordering of the associated models
If you'd like your associated models in a specific order, set the value for this key using an SQL order predicate: "Comment.created DESC", for example.
limit: the maximum number of associated models you'd like Cake to fetch.
For this example, we didn't want to fetch *all* of the user's comments, just five.
foreignKey: the name of the foreign key that points to the associated model.
This is here in case you're working with a database that doesn't follow Cake's naming conventions.
dependent: if set to true, the associated model is destroyed when this one is.
For example, if the "Cool Blue" profile is associated to "Bob", and I delete the user "Bob", the profile "Cool Blue" will also be deleted.
exclusive: If set to true, all the associated objects are deleted in one SQL statement without having their beforeDelete callback run.
Good for use for simpler associations, because it can be much faster.
finderQuery: Specify a complete SQL statement to fetch the association.
This is a good way to go for complex associations that depends on multiple tables. If Cake's automatic assocations aren't working for you, here's where you customize it.
Now, when we execute find() or findAll() calls using the User model, we should see our associated Comment models there as well:
$user = $this->User->read(null, '25');
print_r($user);
//output:
Array
(
[User] => Array
(
[id] => 25
[first_name] => John
[last_name] => Anderson
[username] => psychic
[password] => c4k3roxx
)
[Profile] => Array
(
[id] => 4
[name] => Cool Blue
[header_color] => aquamarine
[user_id] = 25
)
[Comment] => Array
(
[0] => Array
(
[id] => 247
[user_id] => 25
[body] => The hasMany assocation is nice to have.
)
[1] => Array
(
[id] => 256
[user_id] => 25
[body] => The hasMany assocation is really nice to have.
)
[2] => Array
(
[id] => 269
[user_id] => 25
[body] => The hasMany assocation is really, really nice to have.
)
[3] => Array
(
[id] => 285
[user_id] => 25
[body] => The hasMany assocation is extremely nice to have.
)
[4] => Array
(
[id] => 286
[user_id] => 25
[body] => The hasMany assocation is super nice to have.
)
)
)
|
Note |
|---|---|
|
While we won't document the process here, it would be a great idea to define the "Comment belongsTo User" association as well, so that both models can see each other. Not defining assocations from both models is often a common gotcha when trying to use scaffolding. |
Now that you've mastered the simpler associations, let's move to the last assocation: hasAndBelongsToMany (or HABTM). This last one is the hardest to wrap your head around, but it is also one of the most useful. The HABTM association is useful when you have two Models that are linked together with a join table. The join table holds the individual rows that are related to each other.
The difference between hasMany and hasAndBelongsToMany is that with hasMany, the associated model is not shared. If a User hasMany Comments, it is the *only* user associated to those comments. With HABTM, the associated models are shared. This is great for what we're about to do next: associate Post models to Tag models. When a Tag belongs to a Post, we don't want it to be 'used up', we want to continue to associate it to other Posts as well.
In order to do this, we'll need to set up the correct tables for this association. Of course you'll need a "tags" table for you Tag model, and a "posts" table for your posts, but you'll also need to create a join table for this association. The naming convention for HABTM join tables is [plural model name1]_[plural model name2], where the model names are in alphabetical order:
Example 6.8. HABTM Join Tables: Sample models and their join table names
Posts and Tags: posts_tags
Monkeys and IceCubes: ice_cubes_monkeys
Categories and Articles: articles_categories
HABTM join tables need to at least consist of the two foreign keys of the models they link. For our example, "post_id" and "tag_id" is all we'll need.
Here's what the SQL dumps will look like for our Posts HABTM Tags example:
-- -- Table structure for table `posts` -- CREATE TABLE `posts` ( `id` int(10) unsigned NOT NULL auto_increment, `user_id` int(10) default NULL, `title` varchar(50) default NULL, `body` text, `created` datetime default NULL, `modified` datetime default NULL, `status` tinyint(1) NOT NULL default '0', PRIMARY KEY (`id`) ) TYPE=MyISAM; -- -------------------------------------------------------- -- -- Table structure for table `posts_tags` -- CREATE TABLE `posts_tags` ( `post_id` int(10) unsigned NOT NULL default '0', `tag_id` int(10) unsigned NOT NULL default '0', PRIMARY KEY (`post_id`,`tag_id`) ) TYPE=MyISAM; -- -------------------------------------------------------- -- -- Table structure for table `tags` -- CREATE TABLE `tags` ( `id` int(10) unsigned NOT NULL auto_increment, `tag` varchar(100) default NULL, PRIMARY KEY (`id`) ) TYPE=MyISAM;
With our tables set up, let's define the association in the Post model:
Example 6.9. /app/models/post.php hasAndBelongsToMany
<?php
class Post extends AppModel
{
var $name = 'Post';
var $hasAndBelongsToMany = array('Tag' =>
array('className' => 'Tag',
'joinTable' => 'posts_tags',
'foreignKey' => 'post_id',
'associationForeignKey'=> 'tag_id',
'conditions' => '',
'order' => '',
'limit' => '',
'unique' => true,
'finderQuery' => '',
'deleteQuery' => '',
)
);
}
?>
The $hasAndBelongsToMany array is what Cake uses to build the association between the Post and Tag models. Each key in the array allows you to further configure the association:
className (required): the classname of the model you'd like to associate
For our example, we want to specify the 'Tag' model class name.
joinTable: this is here for a database that doesn't adhere to Cake's naming conventions. If your table doesn't look like [plural model1]_[plural model2] in lexical order, you can specify the name of your table here.
foreignKey: the name of the foreign key in the join table that points to the current model.
This is here in case you're working with a database that doesn't follow Cake's naming conventions.
associationForeignKey: the name of the foreign key that points to the associated model.
conditions: SQL condition fragments that define the relationship
We could use this to tell Cake to only associate a Tag that has been approved. You would do this by setting the value of the key to be "Tag.approved = 1", or something similar.
order: the ordering of the associated models
If you'd like your associated models in a specific order, set the value for this key using an SQL order predicate: "Tag.tag DESC", for example.
limit: the maximum number of associated models you'd like Cake to fetch.
Used to limit the number of associated Tags to be fetched.
unique: If set to true, duplicate associated objects will be ignored by accessors and query methods.
Basically, if the associations are distinct, set this to true. That way the Tag "Awesomeness" can only be assigned to the Post "Cake Model Associations" once, and will only show up once in result arrays.
finderQuery: Specify a complete SQL statement to fetch the association.
This is a good way to go for complex associations that depends on multiple tables. If Cake's automatic assocations aren't working for you, here's where you customize it.
deleteQuery: A complete SQL statement to be used to remove assocations between HABTM models.
If you don't like the way Cake is performing deletes, or your setup is customized in some way, you can change the way deletion works by supplying your own query here.
Now, when we execute find() or findAll() calls using the Post model, we should see our associated Tag models there as well:
$post = $this->Post->read(null, '2');
print_r($post);
//output:
Array
(
[Post] => Array
(
[id] => 2
[user_id] => 25
[title] => Cake Model Associations
[body] => Time saving, easy, and powerful.
[created] => 2006-04-15 09:33:24
[modified] => 2006-04-15 09:33:24
[status] => 1
)
[Tag] => Array
(
[0] => Array
(
[id] => 247
[tag] => CakePHP
)
[1] => Array
(
[id] => 256
[tag] => Powerful Software
)
)
)
One important thing to remember when working with associated models is that saving model data should always be done by the corresponding Cake model. If you are saving a new Post and its associated Comments, then you would use both Post and Comment models during the save operation.
If neither of the associated models exists in the system yet (for example, you want to save a new Post and a related Comment at the same time), you'll need to first save the primary, or parent model. To get an idea of how this works, let's imagine that we have an action in our PostsController that handles the saving of a new Post and a related Comment. The example action shown below will assume that you've posted a single Post and a single Comment.
Example 6.10. /app/controllers/posts_controller.php (partial)
function add()
{
if (!empty($this->data))
{
//We can save the Post data:
//it should be in $this->data['Post']
$this->Post->save($this->data);
//Now, we'll need to save the Comment data
//But first, we need to know the ID for the
//Post we just saved...
$post_id = $this->Post->getLastInsertId();
//Now we add this information to the save data
//and save the comment.
$this->data['Comment']['post_id'] = $post_id;
//Because our Post hasMany Comments, we can access
//the Comment model through the Post model:
$this->Post->Comment->save($this->data);
}
}
If, however, the parent model already exists in the system (for example, adding a Comment to an existing Post), you need to know the ID of the parent model before saving. You could pass this ID as a URL parameter, or as a hidden element in a form...
Example 6.11. /app/controllers/posts_controller.php (partial)
//Here's how it would look if the URL param is used...
function addComment($post_id)
{
if (!empty($this->data))
{
//You might want to make the $post_id data more safe,
//but this will suffice for a working example..
$this->data['Comment']['post_id'] = $post_id;
//Because our Post hasMany Comments, we can access
//the Comment model through the Post model:
$this->Post->Comment->save($this->data);
}
}
If the ID was passed as a hidden element in the form, you might want to name the field (if you're using the HtmlHelper) so it ends up in the posted data where it needs to be:
If the ID for the post is at $post['Post']['id']...
<?php echo $html->hidden('Comment/post_id', array('value' => $post['Post']['id'])); ?>
Done this way, the ID for the parent Post model can be accessed at
$this->data['Comment']['post_id'], and is all ready for
a simple
$this->Post->Comment->save($this->data)
call.
These same basic techniques will work if you're saving multiple child models, just place those save() calls in a loop (and remember to clear the model information using Model::create()).
In summary, if you're saving associated data (for belongsTo, hasOne, and hasMany relations), the main point is getting the ID of the parent model and saving it to the child model.
Saving models that are associated by hasOne, belongsTo, and hasMany is pretty simple: you just populate the foreign key field with the ID of the associated model. Once that's done, you just call the save() method on the model, and everything gets linked up correctly.
With hasAndBelongsToMany, its a bit trickier, but we've gone out of our way to make it as simple as possible. In keeping along with our example, we'll need to make some sort of form that relates Tags to Posts. Let's now create a form that creates posts, and associates them to an existing list of Tags.
You might actually like to create a form that creates new tags and associates them on the fly - but for simplicity's sake, we'll just show you how to associate them and let you take it from there.
When you're saving a model on its own in Cake, the tag name (if you're using the Html Helper) looks like 'Model/field_name'. Let's just start out with the part of the form that creates our post:
Example 6.12. /app/views/posts/add.thtml Form for creating posts
<h1>Write a New Post</h1>
<table>
<tr>
<td>Title:</td>
<td><?php echo $html->input('Post/title')?></td>
</tr>
<tr>
<td>Body:<td>
<td><?php echo $html->textarea('Post/body')?></td>
</tr>
<tr>
<td colspan="2">
<?php echo $html->hidden('Post/user_id', array('value'=>$this->controller->Session->read('User.id')))?>
<?php echo $html->hidden('Post/status' , array('value'=>'0'))?>
<?php echo $html->submit('Save Post')?>
</td>
</tr>
</table>
The form as it stands now will just create Post records. Let's add some code to allow us to bind a given Post to one or many Tags:
Example 6.13. /app/views/posts/add.thtml (Tag association code added)
<h1>Write a New Post</h1>
<table>
<tr>
<td>Title:</td>
<td><?php echo $html->input('Post/title')?></td>
</tr>
<tr>
<td>Body:</td>
<td><?php echo $html->textarea('Post/body')?></td>
</tr>
<tr>
<td>Related Tags:</td>
<td><?php echo $html->selectTag('Tag/Tag', $tags, null, array('multiple' => 'multiple')) ?>
</td>
</tr>
<tr>
<td colspan="2">
<?php echo $html->hidden('Post/user_id', array('value'=>$this->controller->Session->read('User.id')))?>
<?php echo $html->hidden('Post/status' , array('value'=>'0'))?>
<?php echo $html->submit('Save Post')?>
</td>
</tr>
</table>
In order for a call to $this->Post->save() in the controller to save the links between this new Post and its associated Tags, the name of the field must be in the form "Tag/Tag" (the rendered name attribute would look something like 'data[ModelName][ModelName][]'). The submitted data must be a single ID, or an array of IDs of linked records. Because we're using a multiple select here, the submitted data for Tag/Tag will be an array of IDs.
The $tags variable here is just an array where the keys are the IDs of the possible Tags, and the values are the displayed names of the Tags in the multi-select element.
You might occasionally wish to change model association information for exceptional situations when building your application. If your association settings in the model file are giving you too much (or not enough) information, you can use two model functions to bind and unbind model associations for your next find.
Let's set up a few models so we can see how bindModel() and unbindModel() work. We'll start with two models:
Example 6.14. leader.php and follower.php
<?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';
}
?>
Now, in a LeadersController, we can use the find() method in the Leader Model to come up with 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 mid-controller.
Example 6.15. leaders_controller.php (partial)
function someAction()
{
//This fetches Leaders, and their associated Followers
$this->Leader->findAll();
//Let's remove the hasMany...
$this->Leader->unbindModel(array('hasMany' => array('Follower')));
//Now a using a find function will return Leaders, with no Followers
$this->Leader->findAll();
//NOTE: unbindModel only affects the very next find function.
//An additional find call will use the configured association information.
//We've already used findAll() after unbindModel(), so this will fetch
//Leaders with associated Followers once again...
$this->Leader->findAll();
}
The unbindModel() function works similarly with other associations: just change the name of the association type and model classname. The basic usage for unbindModel() is:
Example 6.16. Generic unbindModel() example
$this->Model->unbindModel(array('associationType' => array('associatedModelClassName')));
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 only for just the following find function call):
Example 6.17. leaders_controller.php (partial)
funciton anotherAction()
{
//There is no Leader hasMany Principles in the leader.php model file, so
//a find here, only fetches Leaders.
$this->Leader->findAll();
//Let's use bindModel() to add a new association to the Principle 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->findAll();
}
The bindModel() function can be handy for creating new assocations, but it can also be useful if you want to change the sorting or other parameters in a given association on the fly.
There you have it. The basic usage for bindModel is to encapsulate a normal association array inside an array who's key is named after the type of assocation you are trying to create:
Example 6.18. Generic bindModel() example
$this->Model->bindModel(
array('associationName' => array(
'associatedModelClassName' => array(
// normal association keys go here...
)
)
)
);
Please note that your tables will need to be keyed correctly (or association array properly configured) to bind models on the fly.