8

I have a custom content type user_in_club and I'd like to load a single specific node matching two field values. There are 2 ways (I know of) which can solve this:

$result = \Drupal::entityQuery('node')
->condition('type', 'user_in_club')
->condition('field_user_id', $account->id())
->condition('field_club_id',$active_club)
->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($result);

OR

$nodes = \Drupal::entityTypeManager()
->getStorage('node')
->loadByProperties(['type' => 'user_in_club', 'field_user_id' => $account->id(), 'field_club_id' => $active_club ]);

In my single example only one node id is returned, but in case I have multiple node ids returned, is one method to be preferred over the other in terms of performance etc ? I currently don't see a big difference other than ETQ is better to create more complex queries.

3
  • 5
    loadByProperties uses = operator so if you need more advanced conditions, you have to use the query directly.
    – user21641
    Sep 21, 2017 at 10:28
  • Thanks, yes that makes sense. I was just not sure if there is anything else that's different
    – theuni
    Sep 21, 2017 at 10:40
  • 1
    With the lower level entityQuery you can also limit your result set via $query->range(0, 100) as an example. I don't believe you can do that with loadByProperties - correct me if I am wrong. So for smaller result sets loadByProperties might be more practical but as you suggest for more complex or performance-critical queries on large data-sets, entityQuery might be the way to go. Also you could call entityTypeManager()->getStorage('node')->getQuery which effectively does the same thing by exposing the more powerful query interface.
    – Adam
    Feb 12, 2020 at 15:10

1 Answer 1

9

They're identical. loadByProperties() actually converts your conditions to an entity query internally.

I'd acually recommend to do an entity query yourself, directly. It's more readable and loadByProperties() might get deprecated in the future.

3
  • 1
    However, if I see Drupal.php file in core/lib directory, EntityQuery uses entity type manager which by itself uses getQuery, whereas loadByProperties uses getQuery, so I consider the other way round of deprecation as EntityTypeManger is used more than EntityQuery from inside.
    – sarathkm
    Jul 19, 2019 at 9:54
  • 1
    For those writing OOP code, entityQuery() is deprecated in favor of getQuery(). See: drupal.org/node/2849874
    – neuquen
    Jun 15, 2020 at 22:01
  • Note that loadByProperties does a loadMultiple and will load all the entities.
    – mpp
    Nov 24, 2020 at 11:00

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.