I want to merge my two collections,

public function getRelatedPosts()
        if (!$this->hasData('related_posts')) {
            /** collection 1 */
            $collection = $this->_relatedPostsCollection
                ->addFieldToFilter('post_id', ['neq' => $this->getId()])
                ['rl' => $this->getResource()->getTable('magefan_blog_post_relatedpost')],
                'main_table.post_id = rl.related_id',
                'rl.post_id = ?',

            /** collection 2 */
            $collection = $this->_relatedPostsCollection
            ->addFieldToFilter('post_id', ['neq' => $this->getId()])
              ->addFieldToFilter('category_id', ['in' => $this->getCategories()]);
          $collection->getSelect()->columns(['position' => 'post_id']);
                         ['cl' => $this->getResource()->getTable('magefan_blog_post_relatedpost')],
                         'main_table.post_id != cl.related_id',

            $this->setData('related_posts', $collection);


        return $this->getData('related_posts');

How to do that?


1 Answer 1


The merge method returns the merged collection, it doesn't mutate the original collection, thus you need to do the following:

$original = new Collection(['foo']);

$latest = new Collection(['bar']);

$merged = $original->merge($latest); // Contains foo and bar.

Applying the example to your code $related = $collection1->merge($collection2);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.