0

I know how to load an order based on its properties by following code

$orders = \Drupal::entityTypeManager()->getStorage('commerce_order')->loadByProperties(['type' => 'default'])

Since order items is a referenced entity can I load only orders based on purchased entity? Say I have Product Id ($product_id) I need to load orders based on product id. How can I achieve this?

1 Answer 1

0

Get commerce order based on Purchased entity/Product id:

$order_by_product = [];
$orders = \Drupal::entityTypeManager()->getStorage('commerce_order')->loadMultiple();
  foreach ($orders as $order) {
    foreach ($order->getItems() as $order_item) {
      $product_variation = $order_item->getPurchasedEntity();
      // Added condition if product id is 5
      if(isset($product_variation) && $product_variation->getProductId() == 5){
        $order_by_product[$order->id()] = $order;
      }
    }
  }

Background Info: There is not direct relation between the order & product if explore the commerce module that indicates there is not any property in order entity to load order by purchased entity/ product id using loadByProperties(), however by above code can get the order by product id

1
  • Hai thanks for replying. Ya even I couldn't find. Loading all orders will be bit heavy I guess. I was able to filter orders based on product id using views. So I thought what if there is a possibility.
    – Rifas Ali
    Commented Feb 5 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.