I need count the orders of a given customer only if the order contains a specific category, how to modify this to get what I want ?

ex : if the order has a product from the category "watches", I want to count in the result the this query.


Basically I need this :

    $nbOrders = 0;
        foreach($orders as $order){
         $items = $order->getAllItems();
         foreach($items as $item){
          $id = $item->getProductId();
          $categories = $item->getCategory();
          if(in_array("specific category", $categories)) $nbOrders++;


But with factory it would be easier and cleaner

protected $_orderCollectionFactory;
protected $orders;
public function __construct(
    \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
) {
    $this->_orderCollectionFactory = $orderCollectionFactory;
    parent::__construct($context, $data);

public function getOrders()

    if (!$this->orders) {
        $this->orders = $this->_orderCollectionFactory->create()->addFieldToSelect('*')->addFieldToFilter('customer_id',$customerId)->setOrder('created_at','desc');
    return $this->orders;
  • What do you mean if the order contains a specific category? You can explain more..
    – aissyass
    Aug 9, 2019 at 13:24
  • See my updated answer. Aug 9, 2019 at 13:33
  • you need to get all product from the order and the get the category from that product and check the particular category count?
    – aravind
    Aug 9, 2019 at 13:40
  • Only get product is enough to fit into the criteria Aug 9, 2019 at 13:54


Your Answer

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

Browse other questions tagged or ask your own question.