Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create WHERE IN clause with Zend_Db_Select

So I am trying to accomplish something like this:

SELECT * FROM table WHERE status_id IN (1,3,4);

using Zend_Db_Select... can't find how to do it :( Is it at all possible?

like image 814
xelurg Avatar asked Dec 04 '08 06:12

xelurg


4 Answers

you can also use it like this:

$data = array(1,3,4);
$select->where('status_id IN(?)', $data);

you dont need to implode array, and it's safer

like image 114
Martin Rázus Avatar answered Oct 17 '22 18:10

Martin Rázus


The first answer probably works in ZF1 but it doesn't work in Zend Framework 2:

$data = array(1,3,4);
$select->where('status_id IN(?)', $data);

In case the Zend Framework2 I found out that you have to use:

$data = array(1,3,4);
$select->where(array('status_id' => $data));

Result:

WHERE `status_id` IN ('1', '3', '4')

I couldn't find this documented anywhere! ZF documentation is generally sub-optimal.

like image 32
klodoma Avatar answered Oct 17 '22 17:10

klodoma


apparently it is super simple... stupid me:

$select->where('status_id IN(1,3,4)');

:(

like image 8
xelurg Avatar answered Oct 17 '22 17:10

xelurg


We can use Zend\Db\Sql\Predicate\In with Zend\Db\Sql\Where to make a where in query inside a model.

$this->status_ids = array(1,3,4);

// select attributes from db by where in 
$result = $this->select(function (Select $select) {
   $predicate = new In();
   $select->where(
      $predicate->setValueSet($this->status_ids)
                ->setIdentifier('status_id')
      );
})->toArray();
like image 2
Malay M Avatar answered Oct 17 '22 19:10

Malay M