Laravel Eloquent Amount Relationship Column

I am working on a shopping application and now I have come to the next problem.

There is a User, Product, and Cart object.
- The Recycle Bin table contains only the following columns: "id", "user_id", "product_id" and timestamps.
- UserModel "hasMany" Carts (because the user can store multiple products).
- CartModel "belongs" to users and CartModel "hasMany".

Now, to calculate common products, I can just call: Auth::user()->cart()->count() .

My question is: how can I get the SUM () price (product column) of the products in the cart by this user?
I would like to do this with Eloquent and not with a query (mainly because I find it to be much cleaner).

+48
php eloquent laravel relation
Feb 10 '14 at 14:20
source share
3 answers

Auth::user()->products->sum('price');

The documentation makes some of the Collection methods a little easier, but all of the query builder aggregators are apparently available beyond avg() , which can be found at http://laravel.com/docs/queries#aggregates .

+97
Feb 10 '14 at 14:40
source share

I tried to do something similar, and it took me a long time before I could find the collection () function. So you can have something this way:

collection($items)->sum('amount');

This will give you the total amount of all items.

+4
Jan 22 '17 at 5:28
source share

this is not your answer, but for those who come here to look for another problem. I would like to get the sum of a column of a linked table conditionally. There are many types of activities in my transaction database. I wanted to get the amount_total from the Activities table, where activity.deal_id = deal.id and activities.status = paid, so I did it.

 $query->withCount([ 'activity AS paid_sum' => function ($query) { $query->select(DB::raw("SUM(amount_total) as paidsum"))->where('status', 'paid'); } ]); 

he returns

 "paid_sum_count" => "320.00" 

in the "Transactions" attribute.

This is now the amount I wanted to receive, not the invoice.

+1
Nov 09 '17 at 13:50
source share



All Articles