2

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?

0

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>";
 print_r($product->getData());
}  

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

0

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')
            ->joinField('qty',
                'cataloginventory_stock_item',
                'qty',
                'product_id=entity_id',
                '{{table}}.stock_id=1',
                'left'
            )->joinTable('cataloginventory_stock_item', 'product_id=entity_id', ['stock_status' => 'is_in_stock'])
            ->addAttributeToSelect('stock_status')
            ->addFieldToFilter('stock_status', ['eq' => 0])
            ->load();

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.