Reputation: 371
To stay simple, I have a User model which hasMany Post.
[User] id
[Post] id, user_id
How can I write a $this->User->find('all', array('conditions' => $conditions)
to get all User who has no Post ?
Upvotes: 0
Views: 66
Reputation: 1625
Create one function inside User model and try below code: It will give all the User.id having no posts.
$options = array(
'conditions'=>array('Post.id is NULL')
'joins' => array(
array(
'alias' => 'Post',
'table' => ‘posts’,
'type' => 'LEFT',
'conditions' => array(
'Post.user_id = User.id',
),
)
),
'fields' => array('User.id')
);
$returnData = $this->find('list',$options);
Upvotes: 1
Reputation: 9398
assuming Post belongsTo User:
$this->User->Post->find(
'all',
array(
'fields' => array('User.id', 'user_id', 'COUNT(user_id) AS posts_count'),
'group' => 'user_id HAVING posts_count = 0'
)
)
Upvotes: 2