我有这样的模型关系:
Person belongsTo Counselor, PersonType, Program, Term
Person hasMany PersonStage, Text, Mail
PersonStage belongsTo Person, Stage
Stage hasMany PersonStage
本质上,我在舞台和人物之间创建了多对多的关系,但是 PeronStage 表(people_stages)
有一些额外的信息,最重要的是一个created
字段。
我正在尝试做的是查找和分页结果,通常基于 Person 的当前PersonStage,它始终是最新的(带有MAX(people_stages.created)
.)
我不知道如何在 Cake 中实现这一点。我知道在 SQL 中连接查询如下,但我不知道如何在 Cake 中复制它。
SELECT *
FROM people AS p LEFT JOIN (people_stages AS s NATURAL JOIN (
SELECT person_id, MAX(created) created
FROM people_stages
GROUP BY person_id
) t) ON s.person_id = p.id
ORDER BY p.last_name
我尝试了各种连接,都无济于事。这是我没有这些连接的代码:
$this->Paginator->settings = array(
'recursive' => -1,
'contain' => array('Counselor','Term','Program','PersonType'),
'fields' => array('Person.*', 'Counselor.id', 'Counselor.first_name', 'Counselor.last_name', 'Term.*', 'Program.*', 'PersonType.*'),
'order' => array('Person.counselor_read' => 'asc', 'PersonStage.create' => 'desc'),
'limit' => 25
);
$people = $this->Paginator->paginate('Person');