1

Im trying to get all products in a collection: out of stock and products in stock. So what I did is:

/** @var $collection \Magentp\Catalog\Model\ResourceModel\Product\Collection */
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
$collection->addAttributeToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
$collection->sePageSize(3);
$collection->setCurPage(1);

Now, when I use a foreach() loop with $collection->getItems() as the array expression, it just shows the products that have stock, but when I use the $collection->getAllIds() instead, it includes the products out of stock.

Can anyone explain why?

2
  • By default magento filters only in stock products in collection. We have to set the in stock filter as false and follow code this --- magento.stackexchange.com/a/261620/85907 Commented Jun 4, 2020 at 4:28
  • Awesome, that helped me to understand it. You can add it to the answers section so I can mark it as correct :) Commented Jun 5, 2020 at 2:40

1 Answer 1

0

By default magento filters only in stock products in collection. We have to set the in stock filter as false.

$productCollection = $_objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

$collection = $productCollection->create()->setFlag('has_stock_status_filter', false)->load();

And information this link ---

How to get product collection with both in stock and out of stock products in Magento 2.1

Hope this help you

Thanks ...

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.