I have all product collection but I want it sort/order_by by Stock Status.for out-of-stock.
2 Answers
Use below code to your class to filter out of stock product
/**
* @var \Magento\CatalogInventory\Helper\Stock
*/
protected $_stockFilter;
protected $collectionFactory;
on class constructor
public function __construct(
.....
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory,
\Magento\CatalogInventory\Helper\Stock $stockFilter
.....
) {
$this->collectionFactory = $collectionFactory;
$this->_stockFilter = $stockFilter;
}
in your method add the following code
public function getProducts(){
..........
$collection= $this->collectionFactory->create();
$this->_stockFilter->addInStockFilterToCollection($collection);
$collection->addAttributeToSelect('*');
..........
}
here $collection
is product collection.
You can use this method :- \Magento\CatalogInventory\Helper\Stock::addInStockFilterToCollection
like below.
Example:
$collection = $this->productCollectionFactory->create();
$collection->setVisibility($this->catalogProductVisibility->getVisibleInCatalogIds());
$collection = $this->_addProductAttributesAndPrices($collection);
$this->stockFilter->addInStockFilterToCollection($collection);