I use this code to retrieve stock quantity by product id.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
$qty = $StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
This snippet returns only "default source" quantity. My goal consist to retrieve "mycustom source" quantity such as:
Is it possible?
Sure. See below codes:
<?php
namespace YourNameSpace;
use Magento\InventoryApi\Api\SourceItemRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
class YourClass
{
/**
* @var SourceItemRepositoryInterface
*/
protected SourceItemRepositoryInterface $sourceItems;
/**
* @var SearchCriteriaBuilder
*/
protected SearchCriteriaBuilder $searchCriteriaBuilder;
/**
* @param SourceItemRepositoryInterface $sourceItems
* @param SearchCriteriaBuilder $searchCriteriaBuilder
*/
public function __construct(
SourceItemRepositoryInterface $sourceItems,
SearchCriteriaBuilder $searchCriteriaBuilder
){
$this->sourceItems = $sourceItems;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
}
public function yourFunction() {
//Set source
$sku = $product->getSku();
$searchCriteria = $this->searchCriteriaBuilder
->addFilter('sku', $sku)
->create();
$sourceItemData = $this->sourceItems->getList($searchCriteria);
foreach ($sourceItemData->getItems() as $sourceItem){
//Get source qty
$sourceItem->getQuantity()
//Get source code
$sourceItem->getSourceCode();
}
}
}
}
You just need to provide SKU, and then you will get 8 from MyCustom Source and 47 from Default Source. I simplified the codes to be a more readable form, please modify it when you use them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.