3

I have 2 contents who contains a field 'field-test'. The 'field-test' contains an array of taxonomies (its a simple multiple values taxonomy field) :

Node A :

field_test : '1','2','3,'4' // where 1,2,3 and 4 are tids

Node B :

field_test : '4','5','6,'7'

With the entityQuery api, I can get nodes who contains the taxonomy '4' OR '5' with :

$test = \Drupal::entityQuery('node') ->condition('field_test', array('4','5'),'IN') ->execute(); // get nodes A and B in an array 

But I want get only the node B (only the node who contains taxonomies 4 AND 5) How can I do that ?

Thank you :)

2
  • Is there any reason you cannot do ->condition('field_test', 4)->->condition('field_test', 5)? As far as I know the default conjunction for eq is AND. Commented Oct 28, 2016 at 8:13
  • If I do that, the $test->execute() return nothing Commented Oct 28, 2016 at 22:37

2 Answers 2

3

I'm not sure if you can do that using an entity query.

You could specify the delta explicitly:

\Drupal::entityQuery('node') ->condition('field_tags.0.target_id', 1) ->condition('field_tags.1.target_id', 2) ->execute(); 

But of course that would only match if the ids are used in those specific deltas.

You probably need to use raw SQL for this, see https://stackoverflow.com/questions/3918351/sql-query-ensure-a-row-exists-for-each-value-in for the basic approach on how to do this.

3
  • 1
    Hmmm..Drupal query api can't manage all queries ? I mean, If a query become too 'complex', I need use raw query ? I'm surprising ! I thinked drupal api can manage all database request, isn't right ? Commented Oct 28, 2016 at 22:29
  • 1
    No, it can not. The entity query can't do everything. It is designed so that other entity storages can support it too, like MongoDB or even web services. It can not possibly support every possible query and never wil. Commented Oct 29, 2016 at 14:07
  • 1
    That's true if you added the terms in the original order that they are stored in the field. The following will not work : ->condition('field_tags.0.target_id', 2)->condition('field_tags.1.target_id', 1) Commented Dec 1, 2016 at 15:43
3

I had the same problem, and I found a way to do it with entityQuery and an andConditionGroup(). Try this out:

$tags = ['5', '6']; $query = \Drupal::entityQuery('node'); foreach ($tags as $id) { $query->condition($query->andConditionGroup() ->condition('field_tags', $id)); } $query->execute(); 

This should loop over each id, and add it individually to the andConditionGroup().

See this page for more details, including a comment with a very similar example from another user.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.