欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

集合的sum 的查询构建 Builder 的sum 有区别的 有大用 有大大用

$store1 = Store::select('cities.city_id','store_name','stores.store_id',\DB::raw('SUM(shijihuikuan_amount) as shijihuikuan_amounts'),\DB::raw('count(shijihuikuan_id) as shijihuikuan_count'))
   ->joinCity()->leftjoinStoreQianyue()->leftJoinShijihuikuan();

$store1是查询构建器


$shijihuikuan_totals = $store1->groupby('stores.store_id')->get();
$shijihuikuan_total_amounts = $shijihuikuan_totals->sum('shijihuikuan_amount');

这里先获取 get(),再获取 sum 是真实的结果,
因为 sql语句如下 ,结果是好多的sql语句,,,,然后每个结果的 sum(shijihuikuan_amount)值相加 ,这里有条件为  `shijihuikuans`.`deleted_at` is null (事实上是判断所有的表的 deleted_at 为null )
select sum(`shijihuikuan_amount`) as aggregate from `shijihuikuans` where `shijihuikuans`.`store_id` = ? and `shijihuikuans`.`store_id` is not null and `shijihuikuans`.`deleted_at` is null



这里直接查询构器的结果是不对的
$shijihuikuan_totals = $store1->sum('shijihuikuan_amount');
因为 sql语句如下,只有一个sql语句,,只判断了  `stores`.`deleted_at` is null 为null ,所以是不对的
select  * from `stores` inner join `cities` on `stores`.`city_id` = `cities`.`city_id` left join `store_qianyues` on `stores`.`store_id` = `store_qianyues`.`store_id` left join `shijihuikuans` on `stores`.`store_id` = `shijihuikuans`.`store_id` where `stores`.`deleted_at` is null order by `stores`.`store_id` desc
所以 在 上面 ->joinCity()->leftjoinStoreQianyue()->leftJoinShijihuikuan() 这些模型里面的方法里要加上->whereNull() 方法 ,也可以
如下:
public function scopeLeftjoinStoreQianyue($query){
   $query->leftjoin('store_qianyues','stores.store_id','=','store_qianyues.store_id')->whereNull('store_qianyues.deleted_at');
}
public function scopeJoinCity($query){
   $query->join('cities','stores.city_id','=','cities.city_id')->whereNull('cities.deleted_at');
}
public function scopeLeftJoinShijihuikuan($query){
   $query->leftJoin('shijihuikuans','stores.store_id','=','shijihuikuans.store_id')->whereNull('shijihuikuans.deleted_at');
}

普通分类: