0

I have all product collection but I want it sort/order_by by Stock Status.for out-of-stock.

1

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.

0

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.