4

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?

2 Answers 2

5

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)));

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I was actually exploding the string and trimming it but for some reason after combining your and @Anh-Pham answers it seems to work as expected. Thanks!
2
$shortlist = array_map('trim', explode(',',$shortlist)); 

1 Comment

Thanks, I was actually exploding the string and trimming it but for some reason after combining your and @Vins answers it seems to work as expected and hoped. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.