我有一个表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"));
}
]);