Magento – Magento 2.2: how to get out of stock products when managing stock

magento2magento2.2out-of-stockstock

In one of my blocks I want to get a product collection including items that are out of stock, but the product collection always includes WHERE (stock_status_index.stock_status = 1) if you are managing stock.

I don't want out of stock items to show up in categories and search so I do want to manage stock, but in one instance I want to be able to get the products that are out of stock as well.

I have tried all solutions I could find, including:
->joinField('stock_item', 'cataloginventory_stock_item', 'is_in_stock', 'product_id=entity_id', 'is_in_stock=0')

and

$cond = [
    '{{table}}.use_config_manage_stock = 0 AND {{table}}.manage_stock=1 AND {{table}}.is_in_stock=1',
    '{{table}}.use_config_manage_stock = 0 AND {{table}}.manage_stock=0'
];

$cond[] = '{{table}}.use_config_manage_stock = 1';

$collection->joinField(
    'inventory_in_stock',
    'cataloginventory_stock_item',
    'is_in_stock',
    'product_id=entity_id',
    '(' . join(') OR (', $cond) . ')'
);

But everything is negated by the WHERE (stock_status_index.stock_status = 1) part.

EDIT:
$collection->getAllIds() does return the IDs of out of stock products, so I can use that to get the out of stock products via a ProductRepository::getById.

Best Answer

I was facing same issue, but got the solution on git hub forum:

I used this code and it's working fine now. It's a trick, but it worked for me

$collection = $this->_productCollectionFactory->create()
            ->addAttributeToSelect('*')
            ->load();
//**applied below process to load disable products with default 'enable' once.
$collection->clear();
$where = $collection->getSelect()->getPart('where');
foreach ($where as $key => $condition)
 {
     if(strpos($condition, 'stock_status_index.stock_status = 1') !== false){
             $updatedWhere[] = '(stock_status_index.stock_status IN (1,0))';
      } else {
              $updatedWhere[] = $condition;
       }    
  }
 $collection->getSelect()->setPart('where', $updatedWhere);
 $collection->load();

Reference: https://github.com/magento/magento2/issues/13411#issuecomment-361250582

Related Topic