引言
laravel模型提供了query builder对象用于组装查询条件并生成PSD查询语句,从而与数据库对话。 如果使用and约束条件,这并不难写,无非是 A 成立且 B 成立且 C 成立,然后返回某某数据。 但是or查询往往有范围性,在原生SQL内可以使用括号,使其优先级同级,避免查询条件错乱。 但是对于模型内组装的SQL,or条件其实用起来也是步步惊心的。本期我们通过一些例子, 为大家提供避坑指南。
写法
return RoomNews::where('send_id', $uid)->where('rec_id', $otherUid)
->orWhere(function ($query) use ($otherUid, $uid) {
return $query->where('send_id', $otherUid)->where('rec_id', $uid);
})
->where('cate_id', $cateId)
->orderBy('created_at','desc')
->limit(1)
->first();