2
votes

I'm new to ZF2. How can I write a query like this?

SELECT * FROM users WHERE id = 1 AND status != 2

My code Model:

public function getUser($where = array())
    {
        $select = $this->sql->select();
        $select->from(self::TABLE);
        $select->where($where);
        $select->order('name ASC');
        return $statement->execute();
    }

I am using: Zend\Db\Sql

Thanks.

2

2 Answers

1
votes

Look at the docs here. So $where can be a string or Closure, too.

Call it in your case like:

$user = $object->getUser('status != 2');

Oh, I missed the first condition:

$user = $object->getUser(array('id = 1', 'status != 2'));

EDIT:

You can for sure leave the = array() default value. I don't know why but I confused it with type hinting. (array $where)

1
votes
public function getUser( where = array() ) {
    $select = $this->sql->select();
    $select->from(self::TABLE);

    $select
       ->where->nest()
           ->equalTo( 'id' => where['id'] )
           ->or
           ->notEqualTo( 'status' => where['status'] )
       ->unnest();

    $select->order('name ASC');

    return $statement->execute();
}

use like this:

getUser( array(
    'id'     => 1,
    'where'  => 2,
) );