Reputation: 41605
I have something like a blog system. Each entry can has comments. Each comment is created by a User.
I am currently using the read function at my 'view' action on the controller to retrieve all the data.
Relationships between models are already created (belongTo, hasMany ...etc)
When the entry view is called, I get something like this:
['Entry'] => Array
(
[id] => 1
[body] => 'xxxxxx'
[...] => ...
)
[Comment] => Array
(
[0] => Array
(
[id] => 1
[user_id] => 1
[body] => This is an example of a comment guys!
[created] => 0000-00-00 00:00:00
)
[1] => Array
(
[id] => 2
[user_id] => 1
[body] => This is the 2nd comment!!!
[created] => 0000-00-00 00:00:00
)
)
Is there any way, with read function, to retrieve also the "recursive" data of Comments such as the user data related to the user_id? (in order to get their names etc.)
I expect something like this:
['Entry'] => Array
(
[id] => 1
[body] => xxxxxx
[...] => ...
)
[Comment] => Array
(
[0] => Array
(
[Comment] => Array
(
[id] => 1
[user_id] => 1
[body] => This is an example of a comment guys!
[created] => 0000-00-00 00:00:00
)
[User] => Array
(
[id] => 1
[username] => myusername
[created] => 0000-00-00 00:00:00
)
)
[1] => Array
(
[Comment] => Array
(
[id] => 1
[user_id] => 2
[body] => fasdfasfaT
[created] => 0000-00-00 00:00:00
)
[User] => Array
(
[id] => 2
[username] => myusername2
[created] => 0000-00-00 00:00:00
)
)
)
Thanks.
Upvotes: 0
Views: 1964
Reputation: 7847
Yes, it is.
You can control the depth of associations by the recursive
attribute, or rather use the containable
behavior to specify exactly which models you want to include. I always enable this behavior for all models in AppModel.php
($actsAs = array('Containable');
). Then use it like this:
$this->Entry->find('all', array(
...
'contain' => array('Comment' => 'User')
));
The result will look like this:
['Entry'] => Array
(
[id] => 1
[body] => xxxxxx
[...] => ...
)
[Comment] => Array
(
[0] => Array
(
[id] => 1
[user_id] => 1
[body] => This is an example of a comment guys!
[created] => 0000-00-00 00:00:00
[User] => Array
(
[id] => 1
[username] => myusername
[created] => 0000-00-00 00:00:00
)
)
)
In my experience Cake isn't very efficient querying deep associations. In your case it would generate a query for each Comment
to fetch its User
. I would avoid it by letting Cake fetch only the comments, then pluck the user ids of the comments, get all the users with those ids in one query, and then add that user info to the original result.
Upvotes: 1