Magento 2 – Get Products with Quantity Less Than 5

collection;inventorymagento2product

I'm trying to get product collection, only the products which have the qty less than 5 in Magento 2, but I'm failing to load.


use Magento\Framework\App\Bootstrap; 
require DIR . '/../app/bootstrap.php'; 
$bootstrap = Bootstrap::create(BP, $_SERVER); 
$obj = $bootstrap->getObjectManager(); 
$state = $obj->get('Magento\Framework\App\State'); 
$state->setAreaCode('frontend'); 
$productCollection = $obj->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollection->create()
->addAttributeToSelect('*')->load(); 
$collection->addAttributeToFilter('qty',['lt'=>5])

Best Answer

Try this:

use Magento\Framework\App\Bootstrap; 
require DIR . '/../app/bootstrap.php'; 
$bootstrap = Bootstrap::create(BP, $_SERVER); 
$obj = $bootstrap->getObjectManager(); 
$state = $obj->get('Magento\Framework\App\State'); 
$state->setAreaCode('frontend'); 
$productCollection = $obj->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory'); 
$collection = $productCollection->create()->addAttributeToSelect('*');
$collection->joinField(
'qty', 'cataloginventory_stock_item', 'qty', 'product_id=entity_id', '{{table}}.stock_id=1', 'left'
);
$collection->addAttributeToFilter('qty',['lt'=>5]) ->load();