How to execute OR, LIKE condition in WHERE clause in ZF2

I have query like this :

SELECT * FROM `user` WHERE `codedepartment` = <<VALUE>> OR `fullname` LIKE '%<<VALUE>>%'

and i code in model like this :

$sql = new Sql($adapter);
$enim = $sql->select();
$enim->from('user');
$enim->where->equalTo('codedepartment',$jrs)->OR->like('fullname', '%'.$nm_pd.'%');
$statement = $sql->prepareStatementForSqlObject($enim);
$result = $statement->execute();

return $result;

But that's not working. Can you help me ?

Upvotes: 0

Views: 2054

Answers (1)

blackbishop
blackbishop

Reputation: 32660

What you want is to create a where condition with two clauses. It is not simple to figure out how to group your two where clauses. So, maybe you could make use of the Predicates API.

The where method accepts several different datatypes one of which is a PredicateSet, containing, obviously, Predicates. This allows you to group your where clauses.

ZF2: Writing "advanced" MySQL where clauses MySQL

In your case, you could try this code :

$sql = new Sql($adapter);
$enim = $sql->select();
$enim->from('user');
// make changes here
$enim->where(array(
        new \Zend\Db\Sql\Predicate\PredicateSet(
          array(
            new \Zend\Db\Sql\Predicate\Operator('codedepartment',
              \Zend\Db\Sql\Predicate\Operator::OPERATOR_EQUAL_TO, $jrs),
            new \Zend\Db\Sql\Predicate\Like('fullname', '%'.$nm_pd.'%'),
          ),
        \Zend\Db\Sql\Predicate\PredicateSet::COMBINED_BY_OR
       )
));

$statement = $sql->prepareStatementForSqlObject($enim);
$result = $statement->execute();

return $result;

You could also see the documentation for more details.

Please let me know if this works.

Upvotes: 2

Related Questions