I'm importing products and I want to get product by its sku. This is the code:

$product = $this->productFactory->create();
$record = $product->loadByAttribute('sku', '1234');

It works but only with products that have quantity > 0 and product is enabled. How can I find product even if quantity == 0 or status is disabled?


Try using Resource collection,

 $productCollection = $obj->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
 /** Apply filters here */
$collection = $productCollection->addAttributeToSelect('*')
            ->addAttributeToFilter('sku', $sku);
 foreach ($collection as $product){
 echo "<pre>";

This will give you the product details irrespective of status or qty value


Try to use this below code :

$collection = $this->_productFactory->create();
        $collection->setFlag('has_stock_status_filter', true);
        $collection = $collection->addAttributeToFilter('sku', ['eq' => '1234'])->addAttributeToSelect(['name', 'sku'])
            ->addAttributeToSort('created_at', 'DESC')
            )->joinTable('cataloginventory_stock_item', 'product_id=entity_id', ['stock_status' => 'is_in_stock'])
            ->addFieldToFilter('stock_status', ['eq' => 0])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.