[英]Laravel Sum Eloquent sum of multiple multiplications from two different tables
[英]laravel eloquent with sum multiple rows from linked table
我有一个表Quotes
具有与一个一对多的关系QuoteDetails
表。
表结构如下所示:
return $this->quotes->with('quotedetails')
->orderBy('created_at', 'DESC')->paginate(10);
结果是:
{
"current_page":1,
"data":[
{
"id":2,
"subject":"demo",
"quotedetails":[
{
"id":2,
"quotes_id":2,
"description":"testing data",
"total":1080
},
{
"id":3,
"quotes_id":2,
"description":"testing",
"total":180
}
]
},
{
"id":1,
"subject":"demo",
"quotedetails":[
{
"id":1,
"quotes_id":1,
"description":"data",
"total":360
}
]
}
],
"per_page":10,
"prev_page_url":null,
"to":2,
"total":2
}
我想包括quotedetails.total
的总和,而不是QuoteDetails
行的完整列表。 我不确定应该怎么做。
这是我在模型中查询的方式( Quotes
)
public function quotedetails(){
return $this->hasMany('App\Models\QuotesDetail', 'quotes_id', 'id');
}
我如何能得到total
金额。
这是我对输出的期望
{
"current_page":1,
"data":[
{
"id":2,
"subject":"demo link data",
"quotesum": 1260
},
{
"id":1,
"subject":"demo",
"quotesum": 360
}
],
"per_page":10,
"prev_page_url":null,
"to":2,
"total":2
}
$query->withCount([
'quotedetail AS quotesum' => function ($query) {
$query->select(DB::raw("SUM(total) as quotesum"));
}
]);
我知道你想通过查询来实现它,但是在没有查询的情况下,你可以通过这种方式转换分页数据,举个例子:
$quotes = Quotes::whereNotNull('id')->with('quotedetails')
->orderBy('created_at', 'DESC')->paginate();
//transform the data in the Paginate instance
$quotes->getCollection()->transform(function($quote){
$quote->quotesum = $quote->quotedetails->sum('total');
unset($quote['quotedetails']);
return $quote;
});
分页结果中的数据将被转换,并且您拥有所请求的内容。
专业:更多可能在不添加任何查询的情况下对您的响应做更多事情。
Con:结果中的更多数据意味着对集合的更多工作,尤其是在大数据的情况下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.