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.
    – user21641
    Oct 28 '16 at 8:13
  • If I do that, the $test->execute() return nothing Oct 28 '16 at 22:37
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 ? Oct 28 '16 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.
    – Berdir
    Oct 29 '16 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)
    – Adi
    Dec 1 '16 at 15:43
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.