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->field_products as $product) {
$product_ids[] = $product->product_id->value();
}
$orders = commerce_order_load_multiple(array(), array('uid' => $account->uid, 'status' => 'checkout_checkout'));
foreach ($orders as $order) {
$wrapper = entity_metadata_wrapper('commerce_order', $order);
foreach ($wrapper->commerce_line_items as $order_line) {
$product = $order_line->commerce_product;
if (in_array($product->product_id->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).