I want to get total cost of all the order placed by an user programmatically in Drupal 8. I used below code to get total orders count, same way need to get total cost.

$query = \Drupal::entityQueryAggregate('commerce_order')
  ->condition('uid', $user_id)
  ->condition('state', 'completed')
  ->aggregate('order_id', 'COUNT')

I don't know if it will be work or something like this...

$user_id = \Drupal::currentUser()->id();
$orders = \Drupal::entityTypeManager()
->loadByProperties(['uid' => $user_id]); 

$orderPrice = [];
foreach($orders as $key => $value) {
   $orderPrice[] = $value->get('total_price')->getValue()['0']['number'];
$total = array_sum($orderPrice);
  • I think this will not work because unit price is order item level, but what we need is total order price. Also looping through order will have performance issue when there are more order for a user,
    – Viswa
    May 25 at 11:04
  • @Viswa I've edited my answer, is it work for me but... don't know if is it the best practice ;) May 25 at 11:27
  • 1
    Yes that worked for 1000+ orders without any performance issue. Also we shall fine tune the code little bit like instead of $value->get('total_price')->getValue()['0']['number'] we can use $value->getTotalPrice()->getNumber(). Also working on entityQueryAggregate to achieve this without looping, if time permits you can also try.
    – Viswa
    May 26 at 12:31

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.