Combined multiple collections into one collection and display

Hi,

I have three collections.

  • Articles
  • Press releases
  • News

Each document in every of these collections has a datePublished field. How can I combined this collections together and sort them by datePublish.

I am building something like a feed on the homepage.

Advice appreciated. thanks



13.1k

any suggestions on how I can implement in with phalcon ?



2.1k
edited Jun '17

Mysql version

Union https://dev.mysql.com/doc/refman/5.7/en/union.html

(SELECT a FROM t1 WHERE a=10 AND B=1)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2)
ORDER BY a LIMIT 10;

To implement with phalcon, you can use https://docs.phalconphp.com/en/latest/reference/phql.html#using-raw-sql

Php version

but it should be slower

You can try to create an array who store Articles, Press releases, News and sort it by datetime. Something like :

$arrDocuments = array();
foreach($articles as $article){
    $arrDocuments[] = array('datetime' => $article->getDatetime(), 'document' => $article);
}
foreach($pressReleases as $pressRelease){
    $arrDocuments[] = array('datetime' => $pressRelease->getDatetime(), 'document' => $pressRelease);
}
foreach($arrNews as $news){
    $arrDocuments[] = array('datetime' => $news->getDatetime(), 'document' => $news);
}

you can see how sort by datetime there : https://stackoverflow.com/questions/8121241/sort-array-based-on-the-datetime-in-php