CakePHP使用关联模型条件查找

时间:2014-04-30 14:12:08

标签: cakephp

我有3张桌子

Users (id, name, email)

Teams (id, name)

TeamUsers (id, team_id, user_id)

如何查找不在team_id = 1的所有users

1 个答案:

答案 0 :(得分:3)

有很多方法。这是一个:

$model = ClassRegistry::init('User');

$query = 'SELECT * FROM team_users where user_id = User.id AND team_id = 1';

$users = $model->find('all', array(
    'conditions' => array(
        "NOT EXISTS ($query)"
    )
));

这将导致:

SELECT
    *
FROM
    users as User
WHERE
    NOT EXISTS (
        SELECT * FROM team_users WHERE user_id = User.id AND team_id = 1
    )