laravel ORM 中的 withCount 可以統(tǒng)計(jì)相關(guān)聯(lián)數(shù)據(jù)的總數(shù),可以使用下面的方式獲取關(guān)聯(lián)數(shù)據(jù)的 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']])
- 處理關(guān)注人與粉絲的例子
* followers 表
* id user_id follower_id
* 1 2 3 // 用戶3關(guān)注了用戶2置媳。也就是說用戶3是用戶2 的粉絲于樟。
* 2 4 2 // 用戶2關(guān)注了用戶4。也就是說用戶2是用戶4的粉絲拇囊。
* 3 3 2 // 和第一條相反迂曲。兩人互相關(guān)注。 用戶2也是用戶3的粉絲寂拆。
*
*
* belongsToMany(1,2,3,4)
* 四個(gè)參數(shù)意思:
* 1奢米、目標(biāo)model的class全稱呼。
* 2纠永、中間表名
* 3鬓长、中間表中當(dāng)前model對應(yīng)的關(guān)聯(lián)字段
* 4、中間表中目標(biāo)model對應(yīng)的關(guān)聯(lián)字段
*
* 獲取粉絲:(重點(diǎn):這里粉絲也是用戶尝江。所以就把User 模型也當(dāng)粉絲模型來用)
* eg: belongsToMany(User::class,'followers','user_id','follower_id');
* 粉絲表,中間表,當(dāng)前model在中間表中的字段,目標(biāo)model在中間表中的字段涉波。
public function followers()
{
return $this->belongsToMany(User::Class, 'followers', 'user_id', 'follower_id');
}
/**
*用戶關(guān)注人列表
* 關(guān)注人列表,關(guān)聯(lián)表炭序,當(dāng)前model在中間表中的字段啤覆,目標(biāo)model在中間表中的字段。
*/
public function followings(){
return $this->belongsToMany(User::class,'followers','follwer_id','user_id');
}