HABTM并检索所有没有某些模型B的模型A.

时间:2013-02-19 19:10:14

标签: cakephp cakephp-2.1

我有3个表:usersspecialitiesspecialities_users

User HABTM Speciality
Speciality HABTM User
SpecialitiesUser belongsTo Speciality,User

我还有SpecialitiesUser模型。

当我想为特定用户获得专业时,我可以通过

来完成
SpecialitiesUser->find('all' array('conditions' => array('user_id' => $given_user_id));

现在我想获得用户不属于的所有专业。我怎么能在Cake中做到这一点?

1 个答案:

答案 0 :(得分:2)

以下代码中的$other_specialities变量应该是您想要的:

$the_users_specialities = $this->SpecialitiesUser->find('list', array(
    'conditions' => array(
        'SpecialitiesUser.user_id' => $given_user_id
    ),
    'fields' => 'SpecialitiesUser.speciality_id'
));

$other_specialities = $this->Speciality->find('all', array(
    'conditions' => array(
        'NOT' => array(
            'Speciality.id' => $the_users_specialities
        )
    )
));

更新:以下是使用单个查询的方法:

$db = $this->Speciality->getDataSource();

$sub_query = $db->buildStatement(
    array(
        'fields' => array('`SpecialitiesUser`.`speciality_id`'),
        'table' => $db->fullTableName($this->SpecialitiesUser),
        'alias' => 'SpecialitiesUser',
        'conditions' => array('`SpecialitiesUser`.`user_id`' => $given_user_id),
    ),
    $this->Speciality
);

$other_specialities = $this->Speciality->find('all', array(
    'conditions' => array(
        $db->expression('`Speciality`.`id` NOT IN (' . $sub_query . ')')
    )
));