我有一个现有的cakephp(版本2)控制器索引函数执行此操作:
$options = ['Person.name LIKE' => $term];
$this->set('people', $this->Paginator->paginate($options));
在视图中生成一个分页表。
My Person模型引用了约会的子模型,其中一个人有许多约会,如下:
public $hasMany = [
'Appointment' => [
'className' => 'Appointment',
'foreignKey' => 'person_id',
'dependent' => false
]
]
我现在需要在我的表中添加一个Person的最旧约会日期列,即如果使用原始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按常规方式进行排序?
答案 0 :(得分:3)
最简单的方法可能是使用虚拟字段,然后可以将其包含在分页器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'
);
// ...
这将包括子查询并相应地创建所需的别名,并且事情会自动拼接在一起,以便结果看起来好像OldestAppointmentDate
是Person
的实际字段,您可以参考它像任何其他字段一样在paginator helper中,即:
$this->Paginator->sort('Person.OldestAppointmentDate');
另见