Brian Millot
Brian Millot

Reputation: 189

Multiple like in a query with OR

I need to add in this cakephp 3 another "like", the query has to check also in the last_name field. How can i do it, i want to respect the CakePHP 3 rules. thanks.

 $users = $this->Users
        ->find()
        ->where(function ($q) use ($keyword) {
            return $q
            ->like('Users.first_name', "%$keyword%");
            // OR ->like('Users.last_name', "%$keyword%");
        })
        ->limit(5)
        ->toArray();

Upvotes: 2

Views: 253

Answers (2)

arilia
arilia

Reputation: 9398

this should work if you really want to use cakephp expressions

->where(function ($q) use ($keyword) {
    return $q
        ->or_($q->like('Users.first_name', "%$keyword%"))
        ->like('Users.last_name', "%$keyword%");

    })

but you can simply do

->where([
    'OR' => [
        'Users.first_name LIKE' => "%$keyword%",
        'Users.last_name LIKE' => "%$keyword%"
    ]
])

Upvotes: 4

Axiom
Axiom

Reputation: 902

It's not the best way, but this might work:

 $users = $this->Users
        ->find()
        ->where(function ($q) use ($keyword) {
            return $q
            ->like('Users.first_name', "%$keyword% OR Users.last_name LIKE %$keyword%");
        })
        ->limit(5)
        ->toArray();

If that doesn't work, this section of the CakePHP Documentation might help

Upvotes: 0

Related Questions