drupaldrupal-7query-builderor-condition

Drupal 7 OR condition with a series of AND condition


I have a `Drupal query like below

$qry = db_select('table1', 't1');
$qry->addField('t1','etid','entity_id');
$qry->join('node', 'n FORCE INDEX(field1)', 'n.nid = t1.etid');
$qry->join('table2','t2','n.nid = t2.entity_id');
$qry->join('table3','t3','t3.sid=t2.field2');
$qry->condition('t3.field', 'yes', '=');
$qry->condition('n.field', '<value>', 'LIKE');
$qry->condition('t1.field', '<id>', '=');
$qry->condition('n.field', '<value>', '=');
$qry->condition('n.field', <value>, '=');
$qry->condition('t1.field', '<vlaue>', '=');
$qry->orderBy('t1.field','DESC');
$qry->range(0,300);

I would like to add an OR condition to this query. So it will be a global OR condition.

I added a code like below

$or = db_or();
$or->condition('t1.field', [123,456], 'IN');
$qry->condition($or);

But it didn't add an OR condition but put the condition query within braces in an AND condition.

How can I achieve an output query like

where field = value and field = value and field = value OR field = value

by using Drupal query builder? Please help


Solution

  • use db_and

    $db_and = db_and();
    
    
    $qry = db_select('table1', 't1');
    $qry->addField('t1','etid','entity_id');
    $qry->join('node', 'n FORCE INDEX(field1)', 'n.nid = t1.etid');
    $qry->join('table2','t2','n.nid = t2.entity_id');
    $qry->join('table3','t3','t3.sid=t2.field2');
    
    $db_and->condition('t3.field', 'yes', '=');
    $db_and->condition('n.field', '<value>', 'LIKE');
    $db_and->condition('t1.field', '<id>', '=');
    $db_and->condition('n.field', '<value>', '=');
    $db_and->condition('n.field', <value>, '=');
    $db_and->condition('t1.field', '<vlaue>', '=');
    
    $or = db_or();
    $or->condition('t1.field', [123,456], 'IN');
    $or->condition($db_and);
    
    $qry->condition($or);
    
    $qry->orderBy('t1.field','DESC');
    $qry->range(0,300);