laravel - eloquent - 获取相关模型特定列的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26695601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:21:52  来源:igfitidea点击:

laravel - eloquent - get sum of related model specific column

laraveleloquenteager-loading

提问by ciccioassenza

assuming that I have the table

假设我有桌子

orders

订单

with fields

带字段

id, userId, amount, description

id、userId、金额、描述

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}

用户:{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"}

订单:{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}

用户:{id:15,firstName:jim,lastName:morrison,gender:male,orderAmount:50}

Of course I would like to avoid the foreach statement.

当然,我想避免使用 foreach 语句。

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

没有任何运气...

回答by Kristo

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

我会将用户表重命名为用户以遵守 Laravel 约定。 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' );