Get Commerce order by product and user

Problem:

I face an uncommon situation where I needed to get the order by the user who is the customer (or the person who ordered the item) and I also had the id of the product i purchased. Usually what happens is we need to find 

  • What oreders were done by the users
  • What products (commerce_products) are in the order etc:-...

 

Solution:

I had 2 approaches 

  1. Get the users orders and then loop through the orders and the line items find the product and return the specific order
  2. Use the product_id to get the line item and then get the order from the line item

 

I prefer option 2 because it does not require as much as processing as option 1 and it is more soecific
 

So here is the code

/**
 * A function to get the line items that has a given product.
 *
 * @param $product_id
 *
 * @return array|null
 */
function module_name_get_order_line_item_by_product($product_id) {
  $line_item_query = new EntityFieldQuery();
  $results = $line_item_query->entityCondition(
    'entity_type',
    'commerce_line_item',
    '='
  )
    ->fieldCondition('commerce_product', 'product_id', $product_id, '=')
    ->execute();

  if (!empty($results['commerce_line_item'])) {
    $line_items = array_keys($results['commerce_line_item']);
    return $line_items;
  }
  else {
    return NULL;
  }
}
/**
 * A function to get a order by line item and user.
 *
 * @param $line_items
 * @param $user_id
 *
 * @return mixed|null
 */
function module_name_get_orders_by_line_items_and_user(
  $line_items,
  $user_id
) {
  $order_query = new EntityFieldQuery();
  $results = $order_query->entityCondition('entity_type', 'commerce_order', '=')
    ->fieldCondition('commerce_line_items', 'line_item_id', $line_items, 'IN')
    ->propertyCondition('uid', $user_id, '=')->execute();

  if (!empty($results['commerce_order'])) {
    $orders = array_keys($results['commerce_order']);
    return reset($orders);
  }
  else {
    return NULL;
  }
}

 

Hope the code helps you in case you come acorss the problem as well.