5

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.

1 Answer 1

3

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/inventory/blob/develop/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.

2
  • Yes, I did same way before you suggested, but forgot to add answer. Still +1 for you.
    – anonymous
    Apr 25, 2019 at 4:56
  • @Ahmed Osama Jafri URL has been updated.
    – anonymous
    Jun 5 at 6:54

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.