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.
EDIT
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;
}