5

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])
4
  • Can you share your code?
    – kunj
    May 16, 2018 at 16:00
  • 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]) May 16, 2018 at 16:05
  • qty filter not working May 16, 2018 at 16:07
  • is there any way to get collection with qty filters May 16, 2018 at 16:25

1 Answer 1

5

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(); 
6
  • but is there any way to load single product based on qty fiilter May 16, 2018 at 17:12
  • Welcome, happy to help you!! you can try this: $collection->setPageSize(1)->load();
    – kunj
    May 16, 2018 at 17:32
  • @kunj how can we get quantity greater that zero(0) in instock products collections. Sep 24, 2019 at 8:17
  • I tried $collection->addAttributeToFilter('qty',['gt'=>0]) ->load(); but showing error The "qty" attribute name is invalid. Reset the name and try again. Sep 24, 2019 at 8:17
  • @kunj, this will not load any configurable products, bcz all parent has qty 0. how can we get them with this query Feb 26, 2020 at 7:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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