Laravel DB查询 where 优化示例

在数据查询时候,多条件查询,使用场景:

//单个值
$data_where['id'] = 1

// in 条件 写法一
$ids = [1,2,3,4,5];
$data_where[] = [DB::raw("字段名 in ({$ids})"),'1'];
//in条件写法二
$data_where[] = ['in'=>['id'=>$ids]];

$condition[] =['id','in',$ids]; // 这是错误的写法
// Illuminate\Database\Query\Builder关于operators定义中,并没有in
public $operators = [
    '=', '<', '>', '<=', '>=', '<>', '!=',
    'like', 'like binary', 'not like', 'between', 'ilike',
    '&', '|', '^', '<<', '>>',
    'rlike', 'regexp', 'not regexp',
    '~', '~*', '!~', '!~*', 'similar to',
    'not similar to', 'not ilike', '~~*', '!~~*',
];

经测试,上述方法 in 的时候 无法使用。

 

后改为如下实现:

 $check = Db::table('check as c')
->leftJoin('report as  r','r.check_code','=','c.num')
->where(function ($query) use ($user_id,$user_info,$param) {
     //场景一: where 的 或条件
      $query->where(function ($query) use ($name) {
           $query->where('pt.name', '=', $name)->orWhere('p.name', '=', $name);
      });      
     //场景二: in条件
     $query->whereIn('o.scan_doctor_id', [1,2,3]);

})->orderBy('c.update_time','desc')
->select(['r.id'])
->paginate(10);
    A+
发布日期:2020年11月01日 12:28:08  所属分类:Laravel框架
最后更新时间:2020-11-01 12:28:08
头像
  • ¥ 29.0元
  • 市场价:99.0元
  • ¥ 198.0元
  • 市场价:398.0元
  • ¥ 159.0元
  • 市场价:398.0元
  • ¥ 199.0元
  • 市场价:179.0元

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: