2

I have an entity reference inside node. How can I retrieve the parent node?

I tried with the following code, where $node is my entity reference, but it doesn't work.

$entity_ids = $query
    ->condition('type', 'user')
    ->condition('status', 1)
    ->condition('field_product_document', $node->getTitle(),'CONTAINS');

What is wrong in the code? What code should I use?

2
  • Are you sure you need to use $node->getTitle()? I would guess the reference is using the node ID. not the title.
    – avpaderno
    Commented Feb 6, 2016 at 16:11
  • No, Im not sure, I'm trying with id() now
    – monkeyUser
    Commented Feb 6, 2016 at 16:16

3 Answers 3

3

An entity reference field is implemented from the \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem class. If you look at the code for EntityReferenceItem::preSave(), you will notice it is setting its target_id property to $this->entity->id().

public function preSave() {
  if ($this->hasNewEntity()) {
    // Save the entity if it has not already been saved by some other code.
    if ($this->entity->isNew()) {
      $this->entity->save();
    }
    // Make sure the parent knows we are updating this property so it can
    // react properly.
    $this->target_id = $this->entity->id();
  }
  if (!$this->isEmpty() && $this->target_id === NULL) {
    $this->target_id = $this->entity->id();
  }
}

I take your code should be changed to the following one.

$entity_ids = $query
    ->condition('type', 'user')
    ->condition('status', 1)
    ->condition('field_product_document', $node->id());

The change makes also sense: A node title cannot be used to uniquely identify a node, since there could be more nodes with the same title; the node ID uniquely identify a node on a Drupal site.

2

Here is how to do it with entityTypeManager:

$parent_node_results = \Drupal::entityTypeManager()
  ->getListBuilder('node')
  ->getStorage()
  ->loadByProperties([
    'type' => $bundle,
    'status' => 1,
    'field_child_nodes' => $node->id(), //the reference field on the parent
   ]
);

if($parent_node_results) {
  // $parent_node_results is an associative array of parent_id=>parent_entity.
  $parent_node_id = key($parent_node_results);
  $parent_node = $parent_node_results[$parent_node_id];
}
-1

You should be able to get the referenced entity using

$parent = $node->field_product_document->entity;
1
  • 2
    That's the child, not the parent. A query with the node id is the right way, see the comment of kiamlaluno.
    – 4uk4
    Commented Feb 6, 2016 at 21:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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