简体   繁体   中英

Cakephp using an array variable in a find operation

I am creating a shortlist which is stored in a cake Session variable

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

This contains a list of comma separated IDs eg. 1,2,3,4,5

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

I would like to perform a find operation using the comma separated IDs in this variable in the find conditions eg:

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

However, this only returns 1 set of data. If I manually put in an array eg:

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

I get all 5 records returned.

Any ideas how to get around this without performing multiple finds on each id? If I look at the SQL dump I can see WHERE Item . id = ('1,2,3,4,5') using the $shortlist variable whereas if I input it manually as comma delimited integers eg: WHERE Item . id IN (1, 2, 3, 4) then the sql query works as I would like it to. So I guess my question is how to convert a comma delimited string to comma separated integers within a variable so that the SQL does not throw an error?

When you retrieve the session value by using this line $shortlist = $this->Session->read('Item.shorlist'); will be a string, please make sure it be an array.

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

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

$shortlist = array_map('trim', explode(',',$shortlist)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM