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
$joins = array(
array('table'=>'comments',
'alias' => 'Comment',
'type'=>'inner',
'conditions'=> array(
'Comment.id = Vote.comment_id'
)),
array('table'=>'posts',
'alias' => 'Post',
'type'=>'inner',
'conditions'=> array(
'Post.id = Comment.post_id'
)),
array('table'=>'users',
'alias' => 'User',
'type'=>'inner',
'conditions'=> array(
'User.id = Post.user_id','User.id'=>$user_id
))
);
$votes = $this->Vote->find('all',array('joins'=>$joins,'recursive'=>-1));
Use the Containable behavior to perform conditions on associated Models. It took me a bit to dig this up, but it works like a charm! And it uses LEFT JOINs so it will still pull in all values for the original Model.
See documentation.
Something like this should work:
$this->Vote->Behaviors->attach('Containable');
$this->Vote->find('all',array(
'contain'=>array(
'Comment'=>array(
'Post'=>array(
'User'=>array(
'conditions'=>array(
'User.id'=>1,
),
),
),
),
),
));
And if you wanted to include the User data of the person who voted you could simply add one more item to the initial array:
$this->Vote->Behaviors->attach('Containable');
$this->Vote->find('all',array(
'contain'=>array(
'Comment'=>array(
'Post'=>array(
'User'=>array(
'conditions'=>array(
'User.id'=>1,
),
),
),
),
'User',
),
));
Hope that helps!
This may be one of those times you need to use the query method.
SQL calls that you can't or don't want to make via other model methods (careful - there are very few circumstances this is true) can be made using the model's query() method.
$votes = $this->Vote->query('SELECT Vote.* FROM votes Vote
JOIN comments Comment ON (Vote.comment_id = Comment.id)
JOIN posts Post ON (Comment.post_id = Post.id)
JOIN users User ON (Post.user_id = User.id)
WHERE User.id = 1');
This should return an array of Vote entries like the find method would.
foreach ($votes as $vote):
echo $vote['Vote']['id'];
endforeach;
Rather than doing a custom SQL query, you can explicitly join the tables in order to filter by a field of an indirectly associated table. Have a look at this page to see how to join the votes and users through comments: http://book.cakephp.org/view/872/Joining-tables