在Active Record中使用带有多个where子句的find() [英] Using find() in Active Record with multiple where clause

查看:133
本文介绍了在Active Record中使用带有多个where子句的find()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Active Record查询后的内容(使用方括号)分为3组.第一组是从第一个"Where"子句到最后一个"orWhere".第二和第三将使用"andWhere".

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".

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

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

推荐答案

可以这样做:

$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.

请参见官方文档.

这篇关于在Active Record中使用带有多个where子句的find()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆