Reputation: 497
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());
Upvotes: 1
Views: 586
Reputation: 3599
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'];
}
Upvotes: 2