Magento2.3 Product Collection – Filter Product Collection with Source

filtermagento2.3msimulti-source-inventoryproduct-collection

I'm running on Magento 2.3 with MSI(Multi Source Inventory) setup.

I would like to filter product collection with specific source.
Like, I've 4 sources for products, source-1,source-2,source-3 and source-4.
Now I want to get list of SKU which are available in let say source-3.

Example

SKU-1 has 50 qty and its qty divided into 4 sources like below,

source-1 --- 20
source-2 --- 10
source-3 --- 10
source-4 --- 10

What I tried, but it takes too much time to load 🙁

$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');

foreach($collection as $product){
    print_r($product->getData());
    //Magento\InventoryApi\Api\GetSourceItemsBySkuInterface
    $sourceItems = $this->getSourceItemsBySku->execute($product->getSku());
    //print_r($sourceItems->getData());
    foreach($sourceItems as $sourceItem){
        if($sourceItem->getSourceCode() == 'source-3' && $sourceItem->getQuantity() > 0){
            print_r($sourceItem->getData());
            //Magento\Catalog\Api\ProductRepositoryInterface
            $_product = $this->productRepository->get($sourceItem->getSku());
            echo "<br/>";

        }
    }
}

Any idea to optimize this code ? Any help would be really appreciated.

Best Answer

you no need to use Product collection for the purposes you mentioned. You can apply filtering on the level of SourceItemRepository (\Magento\InventoryApi\Api\SourceItemRepositoryInterface::getList) https://github.com/magento-engcom/msi/blob/2.3-develop/app/code/Magento/InventoryApi/Api/SourceItemRepositoryInterface.php#L43

In the search criteria which is passed as a parameter to the getList method you can specify filtering by SKU and/or Source Code.

Related Topic