Question

I'm currently attempting to return all records that match an array of conditions that I have. Currently I can get my code to work, but instead of returning all records that match an array of conditions that I've passed, it just returns the first one and then stops, instead of the four that I know exist in the table I'm accessing. This is with the all parameter set for find.

Here's the code snippet for a better view:

            $array = implode(',', array('1','2','3','4'));

            $a = $this->Assets->find('all', array(
                'conditions' => array(
                    'id' => $array 
                    )
                )   
            );

            var_dump($a);

var_dumping $a will just provide the record that has id 1, when there's records that exist for 2, 3, and 4 as well.

Was it helpful?

Solution

That is the expected result.

You are working against the ORMs auto-magic. Passing a string will result in an equality comparison, ie WHERE x = y, and since id is most probably an integer, the casting will turn the string 1,2,3,4 into 1, so ultimately the condition will be WHERE id = 1.

You should pass the array instead

'conditions' => array(
    'id' => array(1, 2, 3, 4) 
)

that way the ORM will generate an IN condition, ie WHERE id IN (1,2,3,4).

This is also documented in the cookbook:
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#complex-find-conditions

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top