I have a Drupal 8 content entity with a relation to a taxonomy term which allows multiple values. I want to query the entity and get content that has only the terms I use in the query. The problem is I could not find a way to query my entity with multiple taxonomy terms and get the content that are associated with them.
My content entity (node bundle) is called "cocktails" and has among others an entity reference field called "field_ingredients" that has a relation to the taxonomy Vocabulary "Ingredients". I want to get the entity that has for example 2 ingredients with the taxonomy ids: 40 AND 35. I tried the following code without success:
$query = \Drupal::entityQuery('node');
$query->condition('type', 'cocktails');
$query->condition('field_ingredients.entity.tid', 40);
$query->condition('field_ingredients.entity.tid', 35);
$node_ids = $query->execute();
$node_ids are 0
And also this:
$query = \Drupal::entityQuery('node');
$query->condition('type', 'cocktails');
$query->condition('field_ingredients.entity.tid', array(40, 35), 'IN');
$node_ids = $query->execute();
$node_ids are 3 which returns the node ids that have one of the two taxonomy ids (OR logic),
The right answer should be one node id, which is the node that is related to both taxonomy ids, the cocktail with both ingredients
Finally the solution was posted in the actual Drupal API Documentation as a comment
$query->condition(
$query
->andConditionGroup()
->condition('field_ingredients', [40, 35,])
)
);
look at the following link for more details:
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!Query!QueryInterface.php/function/QueryInterface%3A%3AandConditionGroup/8.2.x
on the first comment and first example ("WORKING code")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With