0

I need to add a OR condition to my query so that I can get all nodes related to a particular term. Here is what I have done :

$query = \Drupal::database()->select('taxonomy_index', 'ti');
$query->fields('ti', ['nid']);

// OR CONDITION
$or_group = $query->orConditionGroup()->condition('ti.tid', $params[1], 'IN');

$query->condition('ti.tid', $params[0], 'IN');
$query->condition('ti.status', 1);

// Added OR CONDITION TO QUERY.
$query->condition($or_group);

$query->execute()->fetchAllAssoc('nid');

This is the how the query get build :

QUERY

SELECT ti.nid AS nid

FROM {taxonomy_index} ti

WHERE (ti.tid IN (:db_condition_placeholder_0))

AND (ti.status = :db_condition_placeholder_1)

AND (ti.tid IN (:db_condition_placeholder_2));

PARAMS

Array (

[:db_condition_placeholder_0] => 170

[:db_condition_placeholder_1] => 1

[:db_condition_placeholder_2] => 227

);

As you can see the last "AND" condition should be "OR".

Thanks.

  • Possible duplicate of “OR” condition in db_select() – No Sssweat Jun 21 '18 at 13:56
  • @NoSssweat , I have implemented the same thing as mentioned in drupal.stackexchange.com/a/32771/66332 but somehow it adding the "AND" condition instead of "OR". – Subhash Jun 21 '18 at 14:13
  • You’ve only added one condition to the OR group, so it’s still essentially an AND. Add all OR conditions for that group to that group, not as subsequent ANDs – Clive Jun 21 '18 at 15:37
  • @Clive, thanks for clearing the doubt. I assumed that orConditionGroup adds a 'OR' conditon to the query. – Subhash Jun 22 '18 at 6:40
  • Possible duplicate of "OR" condition in db_select() – Yusef Jul 31 at 18:09
0

The solution seemed to be putting the explicit "IN" in the query, making the simplified version:

$entity_ids = $query
    ->condition('attributes.color', array('red', 'green'), 'IN')
    ->condition('attributes.building_type', 'bikeshed')
    ->execute();

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.