我有3个型号。每个都有一个包含一个名为“created”的DateTime的列在对每个模型执行一个find()之后,我想组合这三个列表并根据这个创建的日期对它们进行排序。在cakephp中有没有一种简单的方法可以做到这一点。这是我使用find()查询数据库的代码片段。我这样做了3次,每个模型一次。有没有办法按照我的描述对这些进行组合和排序?
$this->set('users',
$this->Account->find('all',
array('conditions'=>
array('OR'=>
array('Account.organization_name LIKE'=>'%'.$words.'%',
'Account.first_name LIKE'=>'%'.$words.'%',
'Account.last_name LIKE'=>'%'.$words.'%',
'Account.middle_name LIKE'=>'%'.$words.'%')))),
$this->paginate());
答案 0 :(得分:2)
我通过将所有不同的模型组合成一个数组并对其进行Set::sort
来实现这一点,如下所示:
$allEntities = array();
$articles = $this->Article->find( ... );
foreach ($articles as $k => $v) {
$allEntities[] = $v['Article'];
}
$documents = $this->Document->find( ... );
foreach ($documents as $k => $v) {
$allEntities[] = $v['Document'];
}
$videos = $this->Video->find( ... );
foreach ($videos as $k => $v) {
$allEntities[] = $v['Video'];
}
if (sizeof($allEntities) > 1) {
$allEntities = Set::sort($allEntities, '/created', 'DESC');
}
如果您需要拥有实体的型号名称,您可以这样做:例如:
$videos = $this->Video->find( ... );
foreach ($videos as $k => $v) {
$v['Video']['modelName'] = 'Video';
$allEntities[] = $v['Video'];
}