Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel - eloquent - get sum of related model specific column

assuming that I have the table

orders

with fields

id, userId, amount, description

and the table

user

with various fields

how if I wand to get all the users (with all its fields) and also the sum of the "amount" column of the orders related to that user?

assuming that 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've setted this on my user model

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

And I've tryed this:

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

without any luck...

like image 901
ciccioassenza Avatar asked Nov 02 '14 02:11

ciccioassenza


People also ask

How do I sum a column in laravel 8?

We can easily get the sum of column by using mysql SUM(). So we have two way to get the sum of any column value.At first one is we can do by use laravel sum() of query builder and another one is do directly with select statement by using DB::raw().

How do you find the sum in laravel?

We mostly required to get sum of amount, salary etc in laravel. We can also get sum of column using mysql SUM(). We have two way to get sum of column value. first we can use laravel sum() of query builder and another one we can use with directly with select statement using DB::raw().

What is one to many relation in laravel?

What is One to Many relationship in laravel? A one-to-many relationship is a very basic type of database relationship. When one table refers to many rows in another table that is called a one-to-many relationship.


1 Answers

Some thaughts and hopefully an answer to your question:

I would rename the user table to users to stick to laravel conventions. http://laravel.com/docs/4.2/eloquent#basic-usage

I would name the method in the User model orders

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

To query a user, his orders and sum afterwards his orders amount values:

$userdata = User::with( 'orders' )->where( 'userId', 15 )->first();
$sum = $userdata[ 'orders' ]->sum( 'amount' );
like image 179
Kristo Avatar answered Nov 14 '22 22:11

Kristo