laravel ORM 中的 withCount 可以统计相关联数据的总数,可以使用下面的方式获取关联数据的 sum,avg , max , min:
Orm::withCount(['relation as relation_sum' =>function($query){
$query->select(DB::raw("sum(amount) as relationsum"));
}])
- 获取购买视频的人以及购买视频的订单支付总额
$pay_video_user_list = Video::query()
->with(['payVideoOrders', 'payVideoOrders.user'])
->withCount(['payVideoOrders as pay_video_amount_sum' => function ($query) {
$query->select(\DB::raw("if(sum(amount) <> 0, sum(amount), 0)"));
}])
->where('id', $request->input('id'))
->paginate($limit);
- selectRaw能写多条组合语句
'count(*), min(some_field) as someMin, max(another_field) as someMax'
TakeDeliveryAddress::query()
->selectRaw('*, if(id = ?, 1, 2) as have_default', [$user['default_take_delivery_address_id']])
- 处理关注人与粉丝的例子
* followers 表
* id user_id follower_id
* 1 2 3 // 用户3关注了用户2。也就是说用户3是用户2 的粉丝。
* 2 4 2 // 用户2关注了用户4。也就是说用户2是用户4的粉丝。
* 3 3 2 // 和第一条相反。两人互相关注。 用户2也是用户3的粉丝。
*
*
* belongsToMany(1,2,3,4)
* 四个参数意思:
* 1、目标model的class全称呼。
* 2、中间表名
* 3、中间表中当前model对应的关联字段
* 4、中间表中目标model对应的关联字段
*
* 获取粉丝:(重点:这里粉丝也是用户。所以就把User 模型也当粉丝模型来用)
* eg: belongsToMany(User::class,'followers','user_id','follower_id');
* 粉丝表,中间表,当前model在中间表中的字段,目标model在中间表中的字段。
public function followers()
{
return $this->belongsToMany(User::Class, 'followers', 'user_id', 'follower_id');
}
/**
*用户关注人列表
* 关注人列表,关联表,当前model在中间表中的字段,目标model在中间表中的字段。
*/
public function followings(){
return $this->belongsToMany(User::class,'followers','follwer_id','user_id');
}