1

I have the following query:

$query = \Drupal::entityQuery('node')->condition('type','article');
$result = $query->execute();

Then I want to access all content:

$nodes = \Drupal\node\Entity\Node::loadMultiple(array_keys($result));

But in variable $results, there are wrong NIDs. My first article ID is '12' and second article '13'. But in $result are '9' and '10'

Do you have an explanation for this?

Ok, I found out I can't use array_keys... because keys are not same as IDs. Proved just now in an easy example... in my $result[9] there is the right id '12'.

1 Answer 1

1

The return value of Query::execute,

int|array Returns an integer for count queries or an array of ids. The values of the array are always entity ids. The keys will be revision ids if the entity supports revision and entity ids if not.

Nodes support revisions so the keys will be revision ids and not entity ids.

$nodes = \Drupal\node\Entity\Node::loadMultiple(array_values($result));
4
  • Do you know why to use array_values() in loadMultiple() ? Aug 22, 2021 at 2:06
  • @JoshuaGraham, $result is an associative array of entity ids keyed by revision id. The ::loadMultiple method takes an array parameter expecting entity ids.
    – mradcliffe
    Aug 23, 2021 at 17:12
  • Would Drupal 'try' to load revision ids of 0,1,2,3, etc for array_values() for an array of 4 items them? (they would be the number keys then, instead of the revision id number keys) Aug 26, 2021 at 11:01
  • I'm not sure I understand the question. array_values($result) represents an indexed array of entity ids where as array_keys($result) is an indexed array of Revision ids. ::loadMultiple would try to load entities with entity ids equal to the revision ids in the latter case, which would not be the expected output base don the question.
    – mradcliffe
    Aug 31, 2021 at 19:14

Your Answer

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

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