在带有多个where子句的活动记录中使用find()


Using find() in Active Record with multiple where clause

我想将下面的活动记录查询分为三组(使用括号)。第一组是从第一个"Where"子句到最后一个"orWhere"。第二个和第三个是使用"andWhere"。

请给我关于如何使用括号分隔所有3个部分的建议。

$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');

可以这样做:

$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');

我还为您重构了它,使它现在看起来更可读。不要那样使用串联,这不是一个好的做法。

参见官方文件。