我有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中做到这一点?
答案 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 . ')')
)
));