php - How to sum model relation with id
Get the solution ↓↓↓I'm new to Laravel 7. I faced the problem when summing the total and group by id. Actually I able to produce the sum value however I wish to keep other objects at the same time.
Model
class Invoices extends Eloquent {
public function payments()
{
return $this->hasMany('Payments');
}
}
class Payments extends Eloquent {
public function invoices()
{
return $this->belongsTo('Invoices');
}
}
Expected result
"items": [
{
"sale_id": 1,
"item_id": 1,
"code": "9789814820791",
"qty" :1,
"total": "20.00",
},
{
"sale_id": 1,
"item_id": 2,
"code": "9789814820790",
"qty" :1,
"total": "20.00",
},
"total_amount" : 40,
]
Code
$results = Invoices::with([
'payments' => function ($qry) {
$qry->select(['sale_id', app('db')->raw('sum(total) AS total_amount')])->groupBy('sale_id');
}
])
->get();
With the code above, I'm able to getsale_id
andtotal_amount
however the other result was missing. I did tried added$qry->select(['sale_id','item_id', 'code', 'qty' 'total']);
but it does not work.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: 403 this action is unauthorized.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.