Cakephp using array variable in search operation

I create a list that is stored in the Cake variable of the session

$this->Session->read('Item.shorlist'); 

It contains a list of identifiers separated by commas, for example. 1,2,3,4,5

 $shortlist = $this->Session->read('Item.shorlist'); 

I would like to perform a search operation using comma-separated identifiers in this variable in search terms, for example:

 $shortlist = $this->Item->find('all', array('conditions' => array('Item.id' => array($shortlist)))); 

However, this returns only one data set. If I manually place an array, for example:

 $shortlist = $this->Item->find('all', array('conditions' => array('Item.id' => array(1,2,3,4,5)))); 

I get all 5 entries.

Any ideas how to get around this without doing multiple finds on each identifier? If I look at the SQL dump, I see a WHERE Item . id = ('1,2,3,4,5') using the $ shortlist variable, whereas if I manually enter it as a semicolon, for example: WHERE Item . id IN (1, 2, 3, 4), then the sql query works as I would like. So I assume that my question is how to convert comma-delimited string to comma-separated integers inside a variable so that SQL doesn't throw an error?

+4
source share
2 answers

When retrieving a session value using this line $shortlist = $this->Session->read('Item.shorlist'); there will be a string, make sure it is an array.

Use the explode function $short_list_array = explode(',', $shortlist); to convert it to an array and use

$shortlist = $this->Item->find('all', array('conditions' => array('Item.id' => $short_list_array)));

+5
source
 $shortlist = array_map('trim', explode(',',$shortlist)); 
+2
source

All Articles