ZF2 How to orWhere()

2019-01-23 05:31发布

问题:

I am trying to figure out how to make a Mysql Select with an OR in where Clause. By default all clauses in where statement are ANDed and after some hours of try and fail and looking the net can't make it work. In ZF1 it would be an orWhere() but there is not in ZF2.

This is the code i have inside a AbstracttableGateway:

$resultSet = $this->select(function (Select $select) use ($searchstring) {
             $select->join('users','blog_posts.id_user = users.id',array('name'))
                    ->join('blog_categories','blog_posts.id_category = blog_categories.id', array(
                                           'cat_name'   => 'name',
                                           'cat_alias' => 'alias',
                                           'cat_image'  => 'icon'))
                    ->order('date DESC');
                    //->where("title LIKE '%" .$searchstring . "%' OR content LIKE '%". $searchstring ."%'")
            $select->where->like('content','%'.$searchstring.'%');
            $select->where->like('title','%'.$searchstring.'%');
        }
    );
    return $resultSet;

the lines with the $select->where->like are the ones that are ANDed and I want them with OR. What should I change?

回答1:

There is no orWhere in ZF2, but you could use any combination of Zend\Db\Sql\Predicate objects. For OR use 2 predicates in a PredicateSet with PredicateSet::COMBINED_BY_OR.

There's not much documentation for it, but you could browse the source - for now.

Edit: sample

use Zend\Db\Sql\Predicate;

$select->where(array(
    // ...
    new Predicate\PredicateSet(
        array(
            new Predicate\Like('content', '%'.$searchstring.'%'),
            new Predicate\Like('title', '%'.$searchstring.'%'),
        ),
        Predicate\PredicateSet::COMBINED_BY_OR
    ),
    // ...
));


回答2:

or you cloud use:

$select->where
    ->like('content','%'.$searchstring.'%')
    ->or
    ->like('title','%'.$searchstring.'%');