How to check if a user has ever ordered a product/list of products Given a list of product IDs, I'm trying to determine if a user has ever purchased any of them.

At the moment my logic consists of loading all the orders related to a user, then looping through the order lines to check individual product IDs:

$ordered = FALSE;

$node_wrapper = entity_metadata_wrapper('node', $node);
$product_ids = array();
foreach ($node_wrapper-&gt;field_products as $product) {
  $product_ids[] = $product-&gt;product_id-&gt;value();
}

$orders = commerce_order_load_multiple(array(), array('uid' =&gt; $account-&gt;uid, 'status' =&gt; 'checkout_checkout'));
foreach ($orders as $order) {
  $wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($wrapper-&gt;commerce_line_items as $order_line) {
    $product = $order_line-&gt;commerce_product;
    if (in_array($product-&gt;product_id-&gt;value(), $product_ids)) {
      $ordered = TRUE;
    }
  }
}


This feels like a long way round, and that perhaps I'm missing a helper function somewhere in Commerce that would get me this information.

Anyone know if such a function exists, or if there's a more elegant method to get this data?

NB. I know 'checkout_checkout' isn't the right order status for the production code, this is just test code at the moment. 

I'm looking for an API solution to this; building up an SQL query would obviously be very easy, but more verbose and error-prone. What I'm looking for is a more elegant solution than my existing one (if one exists; it might not).
Here's an alternative approach, using an SQL query

$ordered = FALSE;

$node_wrapper = entity_metadata_wrapper('node', $node);
$product_ids = array();
foreach ($node_wrapper-&gt;field_products as $product) {
  $product_ids[] = $product-&gt;product_id-&gt;value();
}

// Query order details for products
// Note this is the line item product reference table
$query = db_select('field_data_commerce_product', 'p');
// Example if you want more fields, but would need to change -&gt;fetchCol()
// $query-&gt;fields('o', array('order_id', 'order_number', 'uid', 'mail'));
$query-&gt;fields('o', array('uid'));
$query-&gt;innerJoin('field_data_commerce_line_items', 'l', 'l.commerce_line_items_line_item_id = p.entity_id');
$query-&gt;innerJoin('commerce_order', 'o', 'o.order_id = l.entity_id');
$query-&gt;condition('p.commerce_product_product_id', $product_ids, 'IN');
$query-&gt;groupBy('o.order_id');
// Fetch array of uids
$result = $query-&gt;execute()-&gt;fetchCol();

// Check if account-&gt;uid in array of order uids
// If so, uid has ordered product.
if(in_array($account-&gt;uid, $result)){
  $ordered = TRUE;
}