Hi, I am having some issues with CakePHP's find() method and conditions in 'deeper' model associations. There are some of these around but I could not find an answer to this so far.
My model associations are User hasMany Post hasMany Comment hasMany Vote
and Vote belongsTo Comment belongsTo Post belongsTo User
respectively. The belongsTo
associations use inner joins ('type' => 'INNER').
How do I find all comment votes for posts of a specific user with CakePHP's model->find() method?
I used a chain of four models deliberately, because this seems to work for conditions in directly associated models. So there is no using the foreign-key-holding column in the neighbouring table (condition 'Post.user_id == 1' instead of 'User.id == 1').
In SQL this would be:
SELECT v.*
FROM votes v
JOIN comments c ON (v.comment_id = c.id)
JOIN posts p ON (c.post_id = p.id)
JOIN users u ON (p.user_id = u.id)
WHERE u.id = 1
I am unable to reproduce these joins using find() + the Containable behavior. Although I could simply get a user with all his data, I would then have to collect all votes from inside the resulting array.
It is not working like this (Warning: unknown column 'User.id'):
$this->Vote->recursive = 2; // or higher
$this->Vote->find('all',array('conditions' => array('User.id' => 1)));
In fact, this doesn't even work using Post instead of User (Vote->Comment->Post) as soon as I add the condition. The manufactured SQL query only joins votes and comments.
The returning array should only contain votes the SQL query above would return, everything else should be "joined away" in the process.
Note: My question is quite close to this one, which helped me getting started: http://stackoverflow.com/questions/813294/in-cakephp-how-can-i-do-a-find-with-conditions-on-a-realted-field