Out of stock products: why do they appear in Collection::getAllIds and not in Collection::getItems
-
14-04-2021 - |
Question
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?
Solution
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 ...
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange