6

I'm using the Entity reference module and want to select all nodes that has no parent defined. I'm trying with:

$query = new EntityFieldQuery();
$children = $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'page')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_parent', 'target_id', null, 'IS NULL')
    ->execute();

.. but that does not give anything as the field "field_parent" is missing and not set to NULL. If I use IS NOT NULL I get all nodes that has a parent.

How can I select all nodes that has no parent (or is missing the field "field_parent")?


Thanks to Clive I managed to solve this in the following way:

$query = new EntityFieldQuery();
$children = $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'page')
    ->propertyCondition('status', 1)
    ->addTag('filter_no_parent')
    ->execute();

/**
* Implements hook_query_TAG_alter()
*/
function mymodule_query_filter_no_parent_alter(QueryAlterableInterface $query) {
    $query->leftJoin('field_data_field_parent', 'p', 'node.nid = p.entity_id');
    $query->isNull('p.field_parent_target_id');
}
5

You can't (natively) I'm afraid. An EntityFieldQuery doesn't have support for IS NULL or IS NOT NULL.

There are workarounds, however, essentially by adding a tag to the query and implementing a query alter hook, in which you add the required LEFT JOIN and IS NULL statement.

See EntityFieldQuery does not support isNull or isNotNull for a code example. I've used that code before with good results.

  • It worked fine once I understood how to name the tables and fields in the hook_query_TAG_alter function :-) – tirithen Jun 19 '12 at 12:31
  • 3
    Note: Drupal 8 adds the exists and notExists methods. – user49 Jan 18 '13 at 15:25

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