I want to filter product collection by stock and get only In stock products. I have tried multiple ways and followed multiple stack solutions but nothing works as expected.
I am using the Smartwave Porto theme. In the Porto theme, there's is a feature for showing the latest products on the front end. So, I want to filter the latest products collection by stock.
Block File Code:
public function getProducts() {
$count = $this->getProductCount();
$category_id = $this->getData("category_id");
$collection = clone $this->_collection;
$collection->clear()->getSelect()->reset(\Magento\Framework\DB\Select::WHERE)->reset(\Magento\Framework\DB\Select::ORDER)->reset(\Magento\Framework\DB\Select::LIMIT_COUNT)->reset(\Magento\Framework\DB\Select::LIMIT_OFFSET)->reset(\Magento\Framework\DB\Select::GROUP);
if(!$category_id) {
$category_id = $this->_storeManager->getStore()->getRootCategoryId();
}
$category = $this->categoryRepository->get($category_id);
if(isset($category) && $category) {
$collection->addMinimalPrice()
->addFinalPrice()
->addTaxPercents()
->addAttributeToSelect('name')
->addAttributeToSelect('image')
->addAttributeToSelect('small_image')
->addAttributeToSelect('thumbnail')
->addAttributeToSelect($this->_catalogConfig->getProductAttributes())
->addUrlRewrite()
->addCategoryFilter($category)
->addAttributeToSort('created_at','desc');
} else {
$collection->addMinimalPrice()
->addFinalPrice()
->addTaxPercents()
->addAttributeToSelect('name')
->addAttributeToSelect('image')
->addAttributeToSelect('small_image')
->addAttributeToSelect('thumbnail')
->addAttributeToSelect($this->_catalogConfig->getProductAttributes())
->addUrlRewrite()
->addAttributeToSort('created_at','desc');
}
$collection->getSelect()
->order('created_at','desc')
->limit($count);
return $collection;
}
public function getLoadedProductCollection() {
return $this->getProducts();
}
PHTML code:
$_productCollection = $block->getLoadedProductCollection();
I used the below code in the phtml as well as block file as per @davidas answer, but not working:
$_productCollection->setFlag('has_stock_status_filter', true);
$_productCollection = $_productCollection
->joinField('qty',
'cataloginventory_stock_item',
'qty',
'product_id=entity_id',
'{{table}}.stock_id=1',
'left'
)->joinTable('cataloginventory_stock_item', 'product_id=entity_id', array('stock_status' => 'is_in_stock'))
->addAttributeToSelect('stock_status')
->addFieldToFilter('stock_status', ['eq' => 1])
->load();
Note: MSI feature is used in Magento.
Magento version 2.3.3-p1