Search code examples
sqlcakephpfindsql-like

Cakephp: find in a controller using "like" inside an array of possible values


The main idea of this post is that I need to combine search inside an array via "like" without doing a fetch.

In the following code I extract the zones (part of postal code) depending on session ID:

 $sess_id = $this->Session->read('Auth.User');
 $this->loadModel('Zone', 2);
 $MyZones = $this->Zone->find('list', array('recursive' => -1, 'conditions' => array('Zone.user_id' => $sess_id['id']), 'fields' => array('Zone.zone')));
 $this->set('MyZones', $MyZones);

 print_r($MyZones);  
//output : $MyZone = Array ( [1] => AB [2] => AL [3] => B1 )

Now that I have my array I want to look for persons who live in this zone (example his postalcode can be AB526PQ so he lives in the administrator zone)

 $this->loadModel('Person', 2);
 $num_persons = $this->Person->find('count', array('recursive' => -1, 'conditions' => array('Person.pc LIKE' => '%' . $MyZones)));


 $this->set('num_persons', $num_persons);

I got the following error :

Notice (8): Array to string conversion [APP\Controller\ZonesController.php]

This is the generated sql query:

SELECT COUNT(*) AS `count` FROM `tn`.`personnes` AS `Personne` WHERE `Personne`.`pc` LIKE '%Array'

Solution

  • You will have to break your condition from

    $conditions = array('Person.pc LIKE' => '%' . $MyZones);
    

    to

    foreach($MyZones as $MyZone) {
         $conditions[] = array('Person.pc LIKE' => '%' . $MyZone);
    }