3

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

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(); 
  • but is there any way to load single product based on qty fiilter – suresh-vagvala May 16 '18 at 17:12
  • Welcome, happy to help you!! you can try this: $collection->setPageSize(1)->load(); – kunj May 16 '18 at 17:32
  • @kunj how can we get quantity greater that zero(0) in instock products collections. – Hitesh Balpande Sep 24 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. – Hitesh Balpande Sep 24 at 8:17

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.