4

I'm trying to perform a search on two joined columns, fname and lname.

This does not appear to be working:

Object of class Cake\Database\Expression\FunctionExpression could not be converted to string

$users = $this->Users->find();
$users->select(['id', 'fname', 'lname'])
    ->where([$users->func()->concat(['fname', 'lname']).' LIKE' => $terms]);

Any ideas?

Thanks.

ndm
  • 59,784
  • 9
  • 71
  • 110
toast
  • 1,860
  • 2
  • 26
  • 49

3 Answers3

5

If you're concatenating first and last names, they should be concatenated with spaces in between.

$users->select(['id', 'fname', 'lname'])
      ->where(function ($exp, $query) use ($terms) {
         $conc = $query->func()->concat([
            'fname' => 'identifier', ' ',
            'lname' => 'identifier'
         ]);
         return $exp->like($conc, $terms);
       });
Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32
  • 3
    This works. Thanks. I also changed the second like parameter to be (in case someone else has the same problem): like($conc, '%'.$terms.'%'); – toast Sep 27 '16 at 23:32
0

I think you have to use SQL expressions. Try something like this:

->where(function ($exp, $q) use($terms) {
    $concat = $q->func()->concat([
        'fname' => 'identifier', 
        'lname' => 'identifier'
    ]);
    return $exp->like($concat, $terms);
});
arilia
  • 9,373
  • 2
  • 20
  • 44
0

Yu have to use query expression but this can't be done in a pagination array.

So Following ndn suggestion here's how I would do

create a custom finder. In your UsersTable file

public function findByKeyword(Query $query, array $options)
{
    $keyword = $options['keyword'];
    $query->where(
        function ($exp, $q) use($keyword){
            $conc = $q->func()->concat([
                'Users.fname' => 'literal', ù
                'Users.lname' => 'literal']);
            return $exp
                ->or_([
                    'Users.fname LIKE' => "%$keyword%",
                    'Users.lname LIKE' => "%$keyword%",
                ])
                ->like($conc, "%$keyword%");
            }
        );
    return $query;
}

Controller

$this->paginate = [
        'finder' => [
            'byKeyword' => [
                'keyword' => $this->request->data['Users']['keyword']
        ]],
        'conditions' => $limo,  // this will merge your $limo conditions                  
                                // with the ones you set in the custom finder
        'order'= > ['Users.fname desc'],
    ];

$this->set('userlist', $this->paginate($this->Users));
Bhavin Solanki
  • 1,364
  • 11
  • 27