记录一下使用左关联的一次查询(可乐的笔记)
记录一下使用左关联的一次查询
情景描述:
有两个表,一个为users表,一个为库存表:user_storage。两者是一(users)对多(user_Storage)。查出users中等级为3的用户,对应的库存总量并从大到小排序,没有默认为0
那面对这种情况,我的想法就是分组求和:
我第一次写的是:
User::leftJoin('user_storage','users.id','user_storage.user_id')
->where('users.level',3)
->select('users.id','users.mobile',DB::raw("ifnull(sum(user_storage.num) ,0) as total"))
->orderByDesc('total')->take(10)->skip(0)->get();
第一次写的是可以正常查出来的:在user_storage表中不存在的用户用0表示出来了。
但是当我加上条件后:
->where('user_storage.storage_type',0)
加上一句条件后发现user_storage表中不存在用户没有查出来。查了一下文档,发现使用下面的方式是可以查询出来的。(ps:顺便查了下,说使用Eloquent ORM的模型关联也可以实现,不过没有找到具体的实现方法,如君愿教,感激不尽。)
User::leftJoin('user_storage',function($q){
$q->on('users.id','user_storage.user_id')
->where('user_storage.storage_type',0);
})
->where('users.level',3)
->select('users.id','users.mobile',DB::raw("ifnull(sum(user_storage.num) ,0) as total"))
->orderByDesc('total')->take(10)->skip(0)->get();
(当使用左关联时,外部的条件会限制查询范围,使其效果如同Join一样,使用函数闭包的形式,可以限制作用范围)
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: