Search code examples
zend-framework2zend-db

How to apply OR operator in zend2 select query


I am so far able to apply AND and LIKE in zend2 SELECT query, but cannot figure out how to apply OR operator. This is my query:

 $this->table = $data['table'];
    $select = new Select();
    $spec = function (Where $where) {
        $where->like('title', 'border%');
    };
    $select->from($this->table)
            ->where(array('id'=>  8));
    $select->where($spec);
    $resultSet = $this->selectWith($select);
    $resultSet->buffer();
    return $resultSet;

It returns this sql statement

SELECT `rs_morning_report`.*   
FROM `rs_morning_report` 
WHERE `id` = :where1 AND `title` LIKE :where2

Now I want to add "AND (sector LIKE %a% OR sector LIKE %b%)"


Solution

  • You can chain them using the Where object.

    $where = new Where();
    $where->equalTo('fieldOne', 'XX')
        ->AND
        ->equalTo('field_two', 'XXX')
        ->OR
        ->equalTo('field_three', 'XXX')
    ;
    
    $select->where($where);
    

    You can also nest them if you require:

    $where = new Where();
    $where->equalTo('fieldOne', 'XX')
        ->NEST
            ->equalTo('field_two', 'XXX')
            ->OR
            ->equalTo('field_three', 'XXX')
        ->UNNEST
    ;
    
    $select->where($where);