views:

33

answers:

1

I have a find() query with multiple conditions, but the returning array contains entries should be excluded by the conditions. I read in the CakePHP docs that the default operator is "AND", which should mean that the results have to meet every condition, right?

Here is my code, in case something is wrong with that...

$this->set('object', $this->Model->find('all', array('conditions' => 
                          array('Model.field between ? and ?', 
                          array($value1, $value2)), 
                          array('Model.field2 between ? and ?', 
                          array($value3, $value4))));

When I test this, the array is limited by the first condition, but not by the second one (or subsequent ones). Does anyone know what's wrong here?

+1  A: 

This is the correct syntax:

$this->Model->find('all', array('conditions' => array(
    'Model.field BETWEEN ? AND ?' => array($value1, $value2),
    'Model.field2 BETWEEN ? AND ?' => array($value3, $value4))));

Note the double arrow as opposed to a comma on the second and third lines, and the two conditions should be part of the same array.

If that doesn't fix it, you could try forcing it to use AND:

$this->Model->find('all' array('conditions' => array('AND' => array(
    'Model.field BETWEEN ? AND ?' => array($value1, $value2),
    'Model.field2 BETWEEN ? AND ?' => array($value3, $value4)))));
handsofaten
Thank you! I mis-typed the example above and already had used the => as opposed to a comma, but it still wasn't working. However, forcing the AND did work, which is weird because that's supposed to be the default according to the documentation. Regardless, thanks again for the help- it is very much appreciated!
Justin
Glad I could help... yeah, it seemed odd that you would get any results with what you had entered in the question.
handsofaten