There a couple of ways you can go about this. The first would be to use the stock helper Magento\CatalogInventory\Helper\Stock
. This class contains the following two public methods:
addInStockFilterToCollection($collection)
&&
addIsInStockFilterToCollection($collection)
NOTE
is that both of these methods check to see if the config setting for showing out of stock products is enabled.
These methods use the addStockDataToCollection($collection, $isFilterInStock)
from the Magento\CatalogInventory\Model\ResourceModel\Stock\Status
class.
Here the $isFilterInStock variable will either join the stock index table via a left join. Additionally, if this variable is set to true, a stock status filter is added using a where statement. For example:
/**
* @param \Magento\Catalog\Model\ResourceModel\Product\Collection $collection
* @param bool $isFilterInStock
* @return \Magento\Catalog\Model\ResourceModel\Product\Collection $collection
*/
public function addStockDataToCollection($collection, $isFilterInStock)
{
$websiteId = $this->getStockConfiguration()->getDefaultScopeId();
$joinCondition = $this->getConnection()->quoteInto(
'e.entity_id = stock_status_index.product_id' . ' AND stock_status_index.website_id = ?',
$websiteId
);
$joinCondition .= $this->getConnection()->quoteInto(
' AND stock_status_index.stock_id = ?',
Stock::DEFAULT_STOCK_ID
);
$method = $isFilterInStock ? 'join' : 'joinLeft';
$collection->getSelect()->$method(
['stock_status_index' => $this->getMainTable()],
$joinCondition,
['is_salable' => 'stock_status']
);
if ($isFilterInStock) {
$collection->getSelect()->where(
'stock_status_index.stock_status = ?',
Stock\Status::STATUS_IN_STOCK
);
}
return $collection;
}
So to answer your question, use thew addStockDataToCollection method in the Magento\CatalogInventory\Model\ResourceModel\Stock\Status
class and set the $isFilterInStock
variable to true.