分页中的 Cakephp 子查询

Cakephp subquery in paginate

我有一个现有的 cakephp(版本 2)控制器索引函数执行此操作:

$options = ['Person.name LIKE' => $term];
$this->set('people', $this->Paginator->paginate($options));

导致视图中出现分页 table。

我的 Person 模型引用了 Appointment 的子模型,其中一个人有很多约会,如下所示:

public $hasMany = [
    'Appointment' => [
        'className' => 'Appointment',
        'foreignKey' => 'person_id',
        'dependent' => false
    ]
]

我现在需要将一个人最早的约会日期列添加到我的 table,即如果使用原始 SQL,我可能会这样做:

select 
    Person.id,
    Person.name,
    (select 
        min(Appointment.Date) from Appointment
        where Appointment.person_id = Person.id
    ) as OldestAppointmentDate
from Person
where Person.name like 'foo%'

我如何修改 paginate() 参数,使这个新字段包含在结果中,并以通常的方式被 paginate 排序table?

最简单的方法可能是使用虚拟字段,然后您可以将其包含在分页器 fields 选项中,例如:

// in Model/Person.php

public $virtualFields = array(
    'OldestAppointmentDate' => '
        select
            min(Appointment.Date)
        from
            Appointment
        where
            Appointment.person_id = Person.id
    ';
);
// in your controller action

$this->Paginator->settings['fields'] = array(
    'Person.id',
    'Person.name'
    'Person.OldestAppointmentDate'
);

// ...

这将包括子查询并相应地创建所需的别名,然后自动将它们拼接在一起,这样结果看起来就好像 OldestAppointmentDatePerson 的一个实际字段,您可以像任何其他字段一样在分页助手中引用它,即:

$this->Paginator->sort('Person.OldestAppointmentDate');

另见