Score:1

loadByProperties with multiple fields

ru flag

I want to find a node with some values in two fields. To do that, I use loadByProperties in this way:

$nodes = \Drupal::entityTypeManager()  
  ->getStorage('node')
  ->loadByProperties([
    'field_surname' => 'Surname', 
    'field_name' => 'Name',
  ]); 

This does not work. I am sure that at least one node with such values in these fields exists. This code is used in the .module file. When I debug with dpm(), nothing that I passed inside dpm() is displayed. But when I use this function with only one field, everything works fine. Maybe my understanding of loadByProperties is wrong? How can I find nodes based on values in two fields? 

in flag
If I remember correctly, `loadByProperties()` treats multiple conditions with an `AND` under the hood. To have an `OR`, you'll have to manually create the query, which should be the same as how [`loadByProperties()`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityStorageBase.php/function/EntityStorageBase%3A%3AloadByProperties/10) is implemented (get query, add conditions, run execute, load entities), but you construct your condition manually.
No Sssweat avatar
ua flag
`I am sure that at least one node` On said node, go edit it and double check to make sure that on these fields you didn't accidentally add an empty white space before or after the text of your surname and name.
Score:0
in flag

loadByProperties() requires the entity to match all values. If you want to match 'OR' you need to queries with entityTypeManager and combine the results.

$storage = \Drupal::entityTypeManager()  
  ->getStorage('node');

$nidsA = $storage
  ->getQuery()
  ->condition('field_surname', 'Surname')
  ->execute(); 

$nidsB = $storage
  ->getQuery()
  ->condition('field_surname', 'Surname')
  ->execute(); 

$nids = array_merge($nidsA, $nidsB);

$nodes = $storage->loadMultiple($nids);
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.