Drupal Commerce : Dynamic query for getting orders containing a certain product type for a user

Public

Maybe perfectible, but this is the query I found for getting those data

Get raw version
php
  1. $query = db_select('commerce_order', 'o');
  2. $query->join('commerce_line_item', 'cli', 'o.order_id = cli.order_id');
  3. $query->join('commerce_product', 'cp', 'cli.line_item_label = cp.sku');
  4.  
  5. $query->fields('o', array('order_id'))
  6. ->condition('o.uid', $user->uid)
  7. ->condition('o.status', 'cart', '!=')
  8. ->condition('cp.type', $product_type, '=')
  9. ->orderBy('o.changed', 'DESC');