CakePHP与hasMany通过关系分页

时间:2013-10-01 03:14:38

标签: php cakephp

我有这样的模特关系:

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');

1 个答案:

答案 0 :(得分:0)

在获得分页结果之前,您应该遵循这样的标准

在控制器中声明$paginate变量,即PeopleController

public $paginate = array(
    'limit' => 10, // you can set how much you want
    'order' => 'People.last_name'
);

然后在PeopleController的操作中,您希望对结果进行分页,只需设置以您希望的方式获取数据的条件,

public function your_action_name() {
    $this->paginate['contain'] = array('PersonStage');
    $this->Person->Behaviors->load('Containable');
    $people = $this->paginate();
}

希望这会对你有所帮助。