Laravel - eloquent - get the sum of the corresponding column of a specific model

assuming i have a table

Orders

with margins

id, userId, quantity, description

and the table

user

with various fields

as if I earned to receive all users (with all its fields), as well as the amount of the column "sum" of orders associated with this user?

assuming i have:

User: {ID: 15, Firstname: jim, LastName: Morrison, gender: male}

and

order: {id: 1, userId: 15, amount: 10, description: "order xxx"},

order: {id: 3, userId: 15, amount: 40, description: "order yyy"}

I would like to receive:

User: {ID: 15, Firstname: jim, LastName: Morrison, gender: male, orderAmount: 50}

Of course, I would like to avoid the foreach statement.

I installed this in my user model

public function userOrder (){ return $this->hasMany('Order', 'userId'); } 

And I tried this:

 return $this->hasMany('Order', 'userId')->sum('amount'); 

no luck ...

+5
source share
1 answer

Some thaughts and hopefully the answer to your question:

I would rename the user table so that users adhere to the laravel rules. http://laravel.com/docs/4.2/eloquent#basic-usage

I would call this method in user model orders

 public function orders() { return $this->hasMany('Order', 'userId'); } 

To request a user, his orders and the amount after his orders are:

 $userdata = User::with( 'orders' )->where( 'userId', 15 )->first(); $sum = $userdata[ 'orders' ]->sum( 'amount' ); 
+8
source

Source: https://habr.com/ru/post/1206035/


All Articles