所以我的模型关联如下:
人有很多奖
人员列:id、name 奖励列:id、person_id、name
所以人们可以有很多奖项,但我只想检索那些同时获得两个不同奖项的特定人。有没有办法用 find 方法实现这一点?
$persons = $this->Person->find('all', array(
'recursive' => -1,
'conditions' => array(
'AND' => array('Award.name' => 'Award 1', 'Award.name' => 'Award 3')
),
'joins' => array(
array(
'table' =>'awards',
'alias' => 'Award',
'type' => 'LEFT',
'conditions' => 'Award.person_id = person.id'
)
)
)
);
查看页面末尾的子查询。您基本上需要一个子查询,因为您需要查询 Award 表两次以匹配 value1 和 value2。
编辑: 示例代码
$conditionsSubQuery['`Award`.`name`'] = 'value2';
$dbo = $this->Person->getDataSource();
$subQuery = $dbo->buildStatement(
array(
'fields' => array( '`Person2`.`id`'),
'table' => $dbo->fullTableName($this->Person),
'alias' => 'Person2',
'limit' => null,
'offset' => null,
'joins' => array(),
'conditions' => $conditionsSubQuery,
'order' => null,
'group' => null
),
$this->Person
);
$subQuery = ' `Person`.`id` IN (' . $subQuery . ') ';
$subQueryExpression = $dbo->expression($subQuery);
$conditions[] = array('Award.name' => 'value1');
$conditions[] = $subQueryExpression;
$this->Person->find('all', compact('conditions'));
我没有测试它,它可能不起作用,但你明白了。
编辑2: 回答您的评论
所以基本上你想要的 SQL 结果是
select
users.id
from
users
left join
awards
where
awards.name in ('award1', 'award2', 'award3', 'award4')
group by
awards.name
having
count(awards.name) = 4
为此,您可以这样做:
$awards = array('award1', 'award2', 'award3', 'award4');
$this->Person->find(
'all',
array(
'joins' => array(
array(
'table' =>'awards',
'alias' => 'Award',
'type' => 'LEFT',
'conditions' => 'Award.person_id = person.id'
)
),
'conditions' => array(
'Award.name' => $awards,
),
'group' => array('Award.name HAVING '.count($awards))
)
);