【问题标题】:CakePHP Pagination with hasMany through Relationship通过关系使用 hasMany 进行 CakePHP 分页
【发布时间】:2013-10-01 22:05:56
【问题描述】:

我有这样的模型关系:

Person belongsTo Counselor, PersonType, Program, Term
Person hasMany PersonStage, Text, Mail
PersonStage belongsTo Person, Stage
Stage hasMany PersonStage

本质上,我在舞台和人物之间创建了多对多的关系,但是 PeronStage 表 (people_stages) 有一些额外的信息,最重要的是 created 字段。

我试图做的是查找和分页结果,通常基于 Person 的 current 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');

【问题讨论】:

    标签: php cakephp


    【解决方案1】:

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

    在你的控制器中声明$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();
    }
    

    希望对你有所帮助。

    【讨论】:

    • 谢谢。我需要将分页设置保留在方法中,因为它们是不同的——这是在管理方面,而公共方面有不同的要求。分页正在工作,只是我无法弄清楚的加入。
    • 您是否为您的模型使用了可包含的行为?如果没有通过$this->Person->Behaviors->load('Containable');将其加载到您的操作中@
    • 是的,绝对使用 Containable。但问题是,我想选择最近的阶段,而不是用户曾经拥有的所有阶段。
    • 你不想要person.id分组的结果吗,如果需要考虑一下。
    猜你喜欢
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 2013-04-03
    • 1970-01-01
    相关资源
    最近更新 更多