Skip to content

11. How to perform EntityFieldQuery for entities with more than one OG audience field

Alejandro Cremaschi edited this page May 27, 2022 · 3 revisions

This is here to document an alternative way to perform EntityFieldQuery for entities with more than one OG audience field.

Instead of:

    $query = new EntityFieldQuery();
    $result_will_fail = $query
      ->entityCondition('entity_type', 'node')
      ->propertyCondition('type', $node->type)
      ->fieldCondition('og_group1_ref', 'target_id', $group1->nid)
      ->fieldCondition('og_group2_ref', 'target_id', $group2->nid)
      ->execute();

Use:

    $query = new EntityFieldQuery();
    $result1 = $query
      ->entityCondition('entity_type', 'node')
      ->propertyCondition('type', $node->type)
      ->fieldCondition('og_group1_ref', 'target_id', $group1->nid)
      ->execute();

    $query = new EntityFieldQuery();
    $result2 = $query
      ->entityCondition('entity_type', 'node')
      ->propertyCondition('type', $node->type)
      ->fieldCondition('og_group2_ref', 'target_id', $group2->nid)
      ->execute();

    $result_ids = array_intersect(array_keys($result1['node']), array_keys($result2['node']));

Of course, be sure to check that $result1['node'] and $result2['node'] are set before the array_intersect.