1

I have a custom content type that has an entity reference field, that refers to an existing node from a different content type.

I'm performing the query like so

$query = \Drupal::entityQuery('node')
->condition('status', NODE_PUBLISHED)
->condition('type', 'issue');

$nids = $query->execute();

Each of these issue nodes have a field_publication field that refers to a publication node. Each of these publication nodes have a field_permission_category that I'm grabbing like so.

foreach ($nids as $nid) {
   $node = NODE::load($nid);
   $pub = $node->field_publication->entity;
   $pub_permission = $pub->field_permission_category->value;
}

But I want to be able to order the results of the initial query by the value of field_permission_category from the referenced field, but I'm not sure how to go about that, and I'm not even sure that's possible. Basically I want to be able to do

$query = \Drupal::entityQuery('node')
->condition('status', NODE_PUBLISHED)
->condition('type', 'issue')
->sort('field_publication->entity->field_permission_category->value', DESC);

Can you sort a query by a field inside a referenced node?

1
  • Not sure if it does work (don't have time to test) but I think if there was a way it would be something like ->sort('field_publication.entity.field_permission_category')
    – Clive
    Commented Feb 4, 2017 at 16:36

1 Answer 1

4

The answer by Clive is correct. I used this query for a project :

$query->sort('field_projets.entity.field_date_mise_en_prod', 'DESC');

'field_projets' is the field name of the entity reference field on my node.

And 'field_date_mise_en_prod' is the name of a date field belonging to the referenced entity .

You can also use this syntax on conditions. Exemple :

$query->condition('field_tags.entity.name', 'cats');

You asking for a tag with the name 'cats'.

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.