Question

I'm using Drupal 7 and the Commerce module.

I'm trying to warn the user whenever they add to the cart a product they already own. Getting a list of products already owned by the user (in PHP code) seems quite the challenge, because the connection between Line Item and a Product is in a serialized blob.

I have, as arguments, a list of products currently in the cart, and the user.

If I go the way of EntityFieldQuery, I can easily get all line items pertaining to the given products, but I can't extend the query to filter only completed orders by the given user. (Or can I? That would be great.)

If I go the way of db_select, I can easily get all completed orders for the given user, but I can't bridge the Line Item <-> Product connection.

Any help will be appreciated.

Was it helpful?

Solution

Well, here's the answer in case anyone else is interested:

Apparently there's a table called "field_data_commerce_product", which has an "entity_id" column for the Line Item ID, and a "commerce_product_product_id" column for the Product ID. This table allows db_select to easily connect Orders, Line Items, and Products to achieve the kind of query I asked about.

Here's the complete query:

<?php
  // Assuming we have $user populated with the user's ID:
  $query = db_select('commerce_order', 'cord');
  $query->join('commerce_line_item', 'li', 'cord.order_id = li.order_id');
  $query->join('field_data_commerce_product', 'prod', 'li.line_item_id = prod.entity_id');
  $query->condition('cord.uid', $user, '=')
        ->condition('cord.status', 'completed', '=')
        ->fields('prod', array('commerce_product_product_id'));
  $result = $query->execute();
?>

This will return all Product IDs already owned by the given user.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top