/** * Add orders statistics to collection items * * @return $this */ protected function _addOrdersStatistics() { $customerIds = $this->getColumnValues($this->getResource()->getIdFieldName()); if ($this->_addOrderStatistics && !empty($customerIds)) { $connection = $this->orderResource->getConnection(); $baseSubtotalRefunded = $connection->getIfNullSql('orders.base_subtotal_refunded', 0); $baseSubtotalCanceled = $connection->getIfNullSql('orders.base_subtotal_canceled', 0); $totalExpr = $this->_addOrderStatFilter ? "(orders.base_subtotal-{$baseSubtotalCanceled}-{$baseSubtotalRefunded})*orders.base_to_global_rate" : "orders.base_subtotal-{$baseSubtotalCanceled}-{$baseSubtotalRefunded}"; $select = $this->orderResource->getConnection()->select(); $select->from(['orders' => $this->orderResource->getTable('sales_order')], ['orders_avg_amount' => "AVG({$totalExpr})", 'orders_sum_amount' => "SUM({$totalExpr})", 'orders_count' => 'COUNT(orders.entity_id)', 'customer_id'])->where('orders.state <> ?', \Magento\Sales\Model\Order::STATE_CANCELED)->where('orders.customer_id IN(?)', $customerIds)->group('orders.customer_id'); foreach ($this->orderResource->getConnection()->fetchAll($select) as $ordersInfo) { $this->getItemById($ordersInfo['customer_id'])->addData($ordersInfo); } } return $this; }
/** * Orders quantity data * * @param array $productIds * @return array */ protected function getOrdersData(array $productIds) { $ordersSubSelect = clone $this->orderResource->getSelect(); $ordersSubSelect->reset()->from(['oi' => $this->getTable('sales_order_item')], ['product_id', 'orders' => new \Zend_Db_Expr('COUNT(1)')])->where('oi.product_id IN (?)', $productIds)->group('oi.product_id'); return $this->orderResource->getConnection()->fetchAssoc($ordersSubSelect); }