I am very new to EntityFieldQuery. I understand how you create a query with this class. However, I have a node which is referenced (with Entity Reference) by a parent node. I would like to use EntityFieldQuery to retrieve the parent id. Can this be done?
2 Answers
Without extending the class I'm pretty sure not. The reverse relationship isn't defined as a field, so EntityFieldQuery
won't be able to help.
Don't forget entity reference doesn't define a parent/child relationship, it's literally just a relationship from one entity to another. A single entity can be referenced by any number of other entities, so the notion of a single 'parent' doesn't conceptually exist.
If you want more advanced relationships you might consider converting to the Relation module. It has a RelationQuery
class which wraps around EntityFieldQuery
to add relationship-specific functionality.
You can get the parent(s) of a referenced entity using EntityFieldQuery
like this:
<?php
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'PARENT_CONTENT_TYPE')
->propertyCondition('status', 1) // published? yes
->fieldCondition('field_ENTITYREFERENCE_FIELD_NAME', 'target_id', $CHILD_NODE_ID)
->range(0, 10);
$result = $query->execute();
if (isset($result['node'])) {
$items_nids = array_keys($result['node']);
$items = entity_load('node', $items_nids);
}
?>
You'll need to fill in the parent content type, the name of the entity reference field in the parent type and the ID of the child node in this code. The resulting $items
array will contain all parent nodes that reference the child. Since EntityReference doesn't prevent it, there could be more than one parent node referencing the same child so you'll have to enforce a 1-to-1/parent-child relationship yourself.