0

Having trouble figuring out how to filter a product collection by in stock / out of stock status. My goal is to get all out of stock products that also match some other filters:

public function __construct(
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory
  ) {
    $this->collectionFactory = $collectionFactory;
  }

$product = $this->collectionFactory->create()
      ->addAttributeToSelect('*')
      ->addFieldToFilter('quantity_and_stock_status', array('eq' => 0))
      ->addFieldToFilter('supply_discontinued', array('eq' => 1))
      ->addFieldToFilter('status', 1)
      ->addFieldToFilter('visibility', array('in' => array(3,4)))
      ->setPageSize(1)
      ->getFirstItem();

Filtering by quantity_and_stock_status doesn't seem to work in this instance. Is there another way to filter by stock status as well as the other filters I have listed?

1 Answer 1

1

please find a small snippet that may pinpoint where in the Magento core code you can look for code reference

/** @var \Magento\CatalogInventory\Model\ResourceModel\Stock\Status */
    private $stockStatus;

    /**
     * @param $website
     * @return \Magento\Catalog\Model\ResourceModel\Product\Collection
     */
    private function getWebsiteProductInStockCollection($website): \Magento\Catalog\Model\ResourceModel\Product\Collection
    {
        $collection = $this->productCollectionFactory->create();
        $collection->addWebsiteFilter($website->getId());
        $this->stockStatus->addIsInStockFilterToCollection($collection);

        return $collection;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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