We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to build a complex criteria in "Model::find()" conditions?

For example a "user" has many property, like username, email, nick, active, privilege and so on. And I want to filter the records with a keyword and active status (only two vaule, YES and NO).

If keyword is not null, it should filter the records with username like '%keyword%' or email like %keyword%, if it's null, it should show all the records with other conditions.

If active = 'YES' , it should filter the records with that conditions....

How to build this conditons??



77.7k
Accepted
answer
edited Oct '17
User::find([
    'conditions'=>'active = :active: AND (:keyword: IS NOT NULL AND (username LIKE :keyword: OR email LIKE :keyword:)) OR (:keyword: IS NULL AND 1=1)',
    'bind'=>['keyword'=>$keyword, 'active'=>'YES']
])

Or use the modelsManager's createQuery or createBuilder



31.3k

Thanks a lot!