组合多个模型的数据列表,并按cakephp中创建的日期排序 [英] Combining lists of data from Multiple Models and sort them by date created in cakephp

查看:98
本文介绍了组合多个模型的数据列表,并按cakephp中创建的日期排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个模特。每个都有一个列,其中包含一个名为created的DateTime在对每个模型执行find()之后,我想合并3个列表并根据创建的日期对它们进行排序。有一个简单的方法来做这个在cakephp。这里是我使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆