Home » Php » php – Cakephp 3 query with conditions array build in foreach loop

php – Cakephp 3 query with conditions array build in foreach loop

Posted by: admin February 25, 2020 Leave a comment

Questions:

Hello i want to use an array as condition.
For example i have services with a zip as combination

12345 => cleaning,
54321 => cleaning

now i build my array together in a foreach loop

$searcharray = [];
foreach($services as $key => $val){
    searcharray[] = array('service' => $val['service'], 'zip' => $val['zip']);
}

My search array lookes like this:

[
    (int) 0 => [
        'service' => 'cleaning',
        'zip' => '12345'
    ],
    (int) 1 => [
        'service' => 'cleaning',
        'zip' => '54321'
    ]
]

Then i try to get the data from my request table

$this->loadModel('Requests');
$openrequests = $this->Requests->find('all', array(
  'conditions' => array(
    'OR' => array(
      $searcharray
    )
  )
));

It didnt work maybe of the keys in the array, because i set after the $searcharray for example [1] and then it works. I dont want to write the condition as string, but how can i solve it?

How to&Answers:

You have nested the conditions one level too deep.

Your $searcharray is already nested correctly, if you nest it again as in your example, then you’re basically creating an OR node with only one child (which in turn has children itself), which is interpreted as basically “nothing”, as you need at least two children for an operator to be used. The children in the array nested one level deeper will then be interpreted as AND, as that is the default when no operator is specified.

Long story short, just pass $searcharray as is:

'conditions' => [
    'OR' => $searcharray,
]

See also