[英]laravel eloquent with sum multiple rows from linked table
I have a table Quotes
that has a one-to-many relationship with the QuoteDetails
table. 我有一个表Quotes
具有与一个一对多的关系QuoteDetails
表。
The table structure looks like this: 表结构如下所示:
return $this->quotes->with('quotedetails')
->orderBy('created_at', 'DESC')->paginate(10);
Results in: 结果是:
{
"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
}
I want to include the sum of quotedetails.total
rather than the full list of QuoteDetails
rows. 我想包括quotedetails.total
的总和,而不是QuoteDetails
行的完整列表。 I am not sure how this should be done. 我不确定应该怎么做。
Here is how I am querying in my model ( Quotes
) 这是我在模型中查询的方式( Quotes
)
public function quotedetails(){
return $this->hasMany('App\Models\QuotesDetail', 'quotes_id', 'id');
}
How can i get the total
sum. 我如何能得到total
金额。
Here is how i expect the output 这是我对输出的期望
{
"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"));
}
]);
I understand that you want to do it by query, But taking this without even query you'll be able to transform the paginated data this way, giving this example: 我知道你想通过查询来实现它,但是在没有查询的情况下,你可以通过这种方式转换分页数据,举个例子:
$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;
});
The data in the paginated result is transformed and you have what you requested. 分页结果中的数据将被转换,并且您拥有所请求的内容。
Pro: More possibilities to do more with your response without adding any query. 专业:更多可能在不添加任何查询的情况下对您的响应做更多事情。
Con: More data in the result mean more work on the collection especially in case of large data. Con:结果中的更多数据意味着对集合的更多工作,尤其是在大数据的情况下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.