Magento 2 Product Collection – Get All Products Including Out of Stock

magento2product-collection

I have below code in an script outside Magento to get products. It's working fine except it doens't return out of stock products.

How can I add out of stock products to the collection?

// Only gets in stock products
public function getProductsInStock() {
    try {
        $productCollection = $this->objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

        $collection = $productCollection->create()
            ->addAttributeToSelect('sku')
            ->addAttributeToSelect('price')
            ->load();
    } catch (\Exception $e) {
        echo $e->getMessage();
    }
    return $collection;
}

EDIT: I just did some testing. It seems it has to do with following option in backend: Display Out of Stock Products. When it is set to yes the code returns all products instead of just the in stock products.

Is it possible to ignore this setting in any way?

Best Answer

Option 1 You can use Magento\Catalog\Model\ResourceModel\Product\Collection according your needs. You can use can use it to get product data :

Option 2 : Also, You can try below code to get product collection, ( out side of magento ) though this is not best way

Update :

<?php

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection */
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
/** Apply filters here */
$collection = $productCollection->setFlag('has_stock_status_filter', true)->load();

foreach ($collection as $product) {
    echo $product->getSku() . "=>" . $product->getPrice();
}