Using find() in Active Record with multiple where clause

自闭症网瘾萝莉.ら 提交于 2019-12-23 12:00:03

问题


I want to divide (using brackets) following Active Record query in 3 groups. First group would be from first "Where" clause to last "orWhere". Second and third would be using "andWhere".

Please give me suggestions about how can I use brackets to separate all 3 sections.

$query = Book::find()
->where('book_name LIKE :book_name', array(':book_name' => 
'%'.$book_name.'%'))
->orWhere('book_category LIKE :book_category', array(':book_category' =>'%'.$category.'%'))
->orWhere('finance_subcategory LIKE :finance', array(':finance' => '%'.$category.'%'))
->orWhere('insurance_subcategory LIKE :insurance', array(':insurance' => '%'.$category.'%'))
->andWhere('address LIKE :address', array(':address' => '%'.$address.'%'))
->andWhere('status =:status', array(':status' => 'Enabled'))
->orderBy('book_id');

回答1:


Can be done like this:

$query = Book::find()
    ->where([
        'or',
        ['like', 'book_name', $book_name],
        ['like', 'book_category', $category],
        ['like', 'finance_subcategory', $category],
        ['like', 'insurance_subcategory', $category],
    ])
    ->andWhere(['like', 'address', $address])
    ->andWhere(['status' => 'Enabled'])
    ->orderBy('book_id');

I also refactored it for you so it looks more readable now. Don't use concatenation like that, it's not good practice.

See official docs.



来源:https://stackoverflow.com/questions/29357583/using-find-in-active-record-with-multiple-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!