Drupal 7 EntityFieldQuery and Joins (delta_group)
Drupal no longer requires SQL! Yay!
You can no longer use SQL to list your data! What ?
Drupal developers are very used to using SQL to build lists of things. Yeah, views does lists a lot of the time, but, it's not always going to be the right way. Yes, Drupal now has a handy object orientated SQL layer - but that only works for the core tables - it does not work for fields.
When you want tp query on a field value, you create a new EntityFieldQuery object, and assign various conditions to it.The code below is used to select the members of an organic group.
We specify the type of entity we want, "user", and then we say that we want to look at the "gid" column of the "group_audience" field - and select on a specific gid.
Once executed, we will be returned an array of user entity ids, which we are then able to load (using user_load_multiple) and process further.
$query = new EntityFieldQuery;Â Â
$query
 ->entityCondition('entity_type', 'user')
 ->fieldCondition('group_audience', 'gid', $gid);
When you want to add multiple dependant conditions, you need to group your conditions into delta groups.If you don't use the groups, your conditions will not have anything to do with each other, and you might not get the results you are looking for.
A little example. The code below looks like it would select users with a specific group and a specific set of states. However, without a delta_group (the fifth parameter), the state and group are independant. So, if a user is in more than one group, the state returned may not correspond with the group specified.
<code>
// This code will not produce the right results
$query = new EntityFieldQuery;Â Â
$query
 ->entityCondition('entity_type', 'user')
 ->fieldCondition('group_audience', 'gid', $gid)
  ->fieldCondition('group_audience', 'state', (array) $states, 'IN');
Â
Here is my current challenge with Drupal entity field queries.When you create a query object with two columns from the same field, the object will create two joins on the table. Unfortunately, this does not seem to get the results I need.
$query = new EntityFieldQuery;Â Â
$query
 ->entityCondition('entity_type', 'user')
 ->fieldCondition('group_audience', 'gid', $gid)
 ->fieldCondition('group_audience', 'state', (array) $states, 'IN');
Adding a delta_group to the statement means that the conditions are grouped together.
<code>
// This code produces the desired results
$query = new EntityFieldQuery;Â Â
$query
 ->entityCondition('entity_type', 'user')
 ->fieldCondition('group_audience', 'gid', $gid, '=', 0)
 ->fieldCondition('group_audience', 'state', (array) $states, 'IN', 0);