Neelam Gahlyan
Neelam Gahlyan

Reputation: 358

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%)"

Upvotes: 0

Views: 1643

Answers (2)

Vinicius Garcia
Vinicius Garcia

Reputation: 1748

To generate OR statement you can use Zend\Db\Sql\Predicate\PredicateSet with the parameter PredicateSet::COMBINED_BY_OR.

Example:

use Zend\Db\Sql\Predicate;

$select->where(array(
    // Other conditions...
    new Predicate\PredicateSet(
        array(
            new Predicate\Like('sector', '%'.$sectorA.'%'),
            new Predicate\Like('sector', '%'.$sectorB.'%'),
        ),
        Predicate\PredicateSet::COMBINED_BY_OR
    ),
));

Upvotes: 0

Andrew
Andrew

Reputation: 12809

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);

Upvotes: 4

Related Questions