我想总结一个嵌套的集合。
我有以下表格:
venue
可以包含多个offers
,offer
可以有多个orders
。
示例数据可能是:
场地
id | name
==========================
5 | Pizza 4 Less
10 | Poundland
优惠
id | venue_id | name
==================================
17 | 5 | Buy 1 get one free
24 | 5 | 30% off pizza
32 | 10 | 50% off
50 | 10 | 20% off
订单
id | offer_id | bill | paid
===========================
85 | 17 | 15 | true
86 | 17 | 20 | true
87 | 17 | 90 | true
88 | 24 | 14 | true
89 | 32 | 15 | true
90 | 32 | 65 | true
91 | 50 | 24 | true
92 | 50 | 1000 | false
我想使用Laravel Elqouent模型来获取每个场地的总金额。因此,对于上述数据,我希望得到以下结果:
id | name | total_paid
===============================
5 | Pizza 4 Less | 139
10 | Poundland | 104
请注意,总计不包括未支付的订单(即订单92)
我目前的做法如下:
$venues = Venue::with(['offers.orders' => function ($query) {
$query->where('paid', '=', true);
}])
->get();
$totals = [];
foreach ($venues as $venue) {
$totalPaid = 0;
foreach ($venue->offers as $offer) {
$totalPaid += $offer->orders->sum('bill');
}
$totals[$venue->name] = $totalPaid;
}
如您所见,上面的代码效率低且时间长。
有更好的方法吗?
答案 0 :(得分:2)
清理版本,但效率不高
// In your Venue Model
public function getTotalPaidAttribute()
{
return $this->offers->sum('TotalPaid');
}
// In your Offer Model
protected $appends = ['totalPaid'];
public function getTotalPaidAttribute()
{
return $this->orders->sum('paid');
}
// use it :
foreach($venues as $venue){
//do what you want with it
$venue->totalPaid;
}
(编辑)的
正如评论中所说,这种方法可能更清洁,但效率不高:
高效的方式:
// In your Venue Model
public function orders(){
return $this->hasManyThrough(Order::class, Offer::class)
->selectRaw('sum(paid) as aggregate, venue_id')
->groupBy('venue_id');
}
public function totalPaid(){
if ( ! array_key_exists('orders', $this->relations)) $this->load('orders');
$relation = $this->getRelation('orders');
return ($relation) ? $relation->aggregate : 0;
}
public function getTotalPaidAttribute()
{
return $this->totalPaid();
}
也许我搞砸了你的钥匙,你可能不得不使用关系的完整声明:
return $this->hasManyThrough(
Order::class, Offer::class
'venue_id', 'offer_id', 'id'
);
但我刚刚完成了我的项目,它就像一个魅力