4

我想将 Active Record 查询分成 3 组(使用括号)。第一组将从第一个“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');
4

1 回答 1

13

可以这样做:

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

我还为您重构了它,因此它现在看起来更具可读性。不要像那样使用连接,这不是一个好习惯。

官方文档

于 2015-03-31T03:40:26.883 回答