组合来自多个模型的数据列表并按在 cakephp 中创建的日期对它们进行排序 [英] Combining lists of data from Multiple Models and sort them by date created in cakephp
问题描述
我有 3 个模型.每个都有一个包含名为created"的 DateTime 的列在对每个模型执行 find() 之后,我想组合 3 个列表并根据此创建日期对它们进行排序.在 cakephp.ini 中是否有一种简单的方法可以做到这一点.这是我使用 find() 查询数据库的代码片段.我这样做了 3 次,每个模型一次.有没有办法像我描述的那样组合和排序这些?
I have 3 Models. Each one has a column that holds a DateTime called "created" After performing a find() on each model, I would like to combine the 3 lists and sort them according to this created date. Is there an easy way to do this in cakephp. Here is the code snippet where I use find() to query the database. I do this 3 times, once with each Model. Is there a way to combine and sort these as I have described?
$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());
推荐答案
我通过将所有不同的模型组合到一个数组中并在其上执行 Set::sort
来做到这一点,如下所示:>
I do that by combining all the different models into one array and doing Set::sort
on that, like this:
$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');
}
如果您需要实体的模型名称,您可以这样做,例如:
If you need to have a model name for the entities, you can do that for example like this:
$videos = $this->Video->find( ... );
foreach ($videos as $k => $v) {
$v['Video']['modelName'] = 'Video';
$allEntities[] = $v['Video'];
}
这篇关于组合来自多个模型的数据列表并按在 cakephp 中创建的日期对它们进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!