0

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()])
                ->addStoreFilter($this->getStoreId());
            $collection->getSelect()->joinLeft(
                ['rl' => $this->getResource()->getTable('magefan_blog_post_relatedpost')],
                'main_table.post_id = rl.related_id',
                ['position']
            )->where(
                'rl.post_id = ?',
                $this->getId()
            );


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


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

        }


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

How to do that?

4

1 Answer 1

0

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.