6

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...

ciccioassenza
  • 233
  • 1
  • 7
  • 17

1 Answers1

8

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' );
Kristo
  • 547
  • 1
  • 7
  • 20
  • Thanks for the reply. I was very vague in defining my tables...of course it is called "users" and my model is called "User", but I am afraid yours is not the solution I'm looking for... Take a look at [this]:http://stackoverflow.com/questions/25655388/get-max-value-for-each-related-model-with-eloquent-in-laravel and see how Jarek Tkaczyk solved my problem with "latest()" function...i looking for something like that – ciccioassenza Nov 02 '14 at 13:16
  • ah oh ... I don´t see that in your question but hey, I´m happy you found your solution :-) – Kristo Nov 02 '14 at 13:25
  • Forgive me, my English is bad and I have trouble explaining the issue... the link I posted is related to another question where what I wanted to point out is how with that solution I was able to take only the last message among those related, without use a foreach. The problem persists :( – ciccioassenza Nov 02 '14 at 14:40
  • Just found out you can use the sum function even in loop in blade templates. So if you have many orders you can use @foreach($users as $user) {{$user->orders->sum('amount')}} @endforeach – Raja Amer Khan Mar 11 '16 at 10:51