The article entity has an unlimited multi-value Taxonomy reference field field_article_countries
referencing the Taxonomy vocabulary Countries
and the User entity has a single value Taxonomy reference field field_user_countries
which referencing the same taxonomy vocabulary Countries
.
Programmatically, and comparing to one specific Article, I want to load all users that has have their field_user_countries
value = to one of the values available inside the multi-value Taxonomy reference field field_article_countries
.
Example:
Say Article "ABC" has the field_article_countries
with values:
- Paris
- Spain
- London
- Italy
User "A" has field_user_countries
set to:
- Spain
User "B" has field_user_countries
set to:
- Italy
and User "C" has field_user_countries
set to:
- Turkey
I want programmatically, and based on Article "ABC", to load only User A & User B.
Below is my code:
// Get in array, a list of all "Article Countries" available for the loaded article.
$Article_Countries = $article->field_article_countries->getString();
// Get Entity Manager to build your query
$storage = \Drupal::entityTypeManager()
->getStorage('user');
// Get all Users satisfing your conditions
// For Condition Parameters @See: https://www.drupal.org/docs/8/api/database-api/dynamic-queries/conditions
$uids = $storage->getQuery()
->accessCheck(FALSE)
//->condition1
//->condition2
->condition('field_user_countries', $Article_Countries, 'IN')
->execute();
// Load all User entities according to their IDs
$users = \Drupal\user\Entity\User::loadMultiple($uids);
// Loop through loaded users.
foreach ($users as $user) {
// Do something here.
}
The problem is that only one user is being loaded and not all users !
Any idea what is wrong with my code ?