1

我有 3 张桌子:users, specialities, specialities_users.

User HABTM Speciality
Speciality HABTM User
SpecialitiesUser belongsTo Speciality,User

我也有模型SpecialitiesUser

当我想为给定用户获取专业知识时,我可以通过

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

现在我想获取用户不属于的所有专业。我如何在 Cake 中做到这一点?

4

1 回答 1

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 . ')')
    )
));
于 2013-02-20T02:48:23.200 回答