Magento – Magento 2: Merge multiple collections

collection;magento2

For a configurable product I want to get all related products of the linked simple products. How is it possible to merge multiple collections?

At the moment I overwrite the related products on each iteration of the foreach loop.

$product = $this->_coreRegistry->registry('product');
/* @var $product \Magento\Catalog\Model\Product */

if ($product->getTypeId() === 'configurable') {
    $simpleProducts = $product->getTypeInstance()->getUsedProducts($product);
}

$relatedProductCollection = false;
/* @var $simpleProduct \Magento\Catalog\Model\Product */
foreach ($simpleProducts as $simpleProduct) {
    /** @var $relatedProductCollection \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection */
    $relatedProductCollection = $simpleProduct->getRelatedProductCollection()->addAttributeToSelect(
        'required_options'
    )->setPositionOrder()->addStoreFilter();
}

Best Answer

I am assuming that you know how to get id as you said , here is logic :

1- Initialize an array for ex: $productids[] = $product->getId().

2- Store all product id into single array (you can also use array merge if you have id in different array's).

3- Then array_unique($productid);

create model class for product collection for example: app/code/Vendor/ModuleName/Model/Product.php

public function __construct(
        \Magento\Catalog\Model\Product $product
    )
{
    $this->product = $product;
}

public function getCollection($productIds)  //array of product id's
{
    $collection = $this->product->create()->getCollection()
      ->addFieldToFilter('entity_id', array('in' => $productIds))
    ->addAttributeToSelect('*');
    return $collection;
}