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.

5
  • Possible duplicate of “OR” condition in db_select()
    – No Sssweat
    Jun 21, 2018 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, 2018 at 14:13
  • 1
    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, 2018 at 15:37
  • @Clive, thanks for clearing the doubt. I assumed that orConditionGroup adds a 'OR' conditon to the query.
    – Subhash
    Jun 22, 2018 at 6:40
  • Possible duplicate of "OR" condition in db_select()
    – Yuseferi
    Jul 31, 2019 at 18:09

2 Answers 2

1

If you really want to use an or then it should be

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

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

$query->condition('ti.status', 1);

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

$query->execute()->fetchAllAssoc('nid');
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 and acknowledge that you have read and understand our privacy policy and code of conduct.

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