CakePHP Concatenation

by | May 21, 2014

I had to concatenate two fields to search them as a single string. Another programmer created a table of phone numbers with the columns area_code (INT 3) and phone_number (INT 7) respectively. But people were searching for all ten digits as a single unit, so I needed to search both the columns as a single field.

This blog post on virtual fields and this doc about same made me think that  $virtual_fields was the answer, but it didn’t work out for me. The following solution worked well enough.

$conditions = array(
'CONCAT(NoCallList.area_code, NoCallList.phone_number) LIKE' => '%' . $this->data['NoCallList']['search_term'] . '%'
);
$this->set('items' , $this->{$this->modelClass}->find('all'
, array(
'order'=>array($this->modelClass . '.phone_number')
, 'limit'=>500
, 'conditions'=>$conditions
,
)
));