Laravel 关系总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31853838/
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
Laravel Sum of relation
提问by Hardist
I want to return the sum of "amount" from my payments table. There can be many payments for one invoice. The below "->sum('amount') does not work, it returns:
我想从我的付款表中返回“金额”的总和。一张发票可以有多次付款。下面的 "->sum('amount') 不起作用,它返回:
Call to a member function addEagerConstraints() on a non-object.
在非对象上调用成员函数 addEagerConstraints()。
How to return the sum of all payments for each invoice in my relation?
如何返回我关系中每张发票的所有付款总额?
Invoices Model:
发票模型:
class Invoices extends Eloquent {
public function payments()
{
return $this->hasMany('Payments')->sum('amount');
}
}
Expenses Model:
费用模型:
class Payments extends Eloquent {
public function invoices()
{
return $this->belongsTo('Invoices');
}
}
My table "payments" holds the foreign key of my tables invoices, which is invoices_id.
我的表“付款”保存我的表发票的外键,即发票 ID。
回答by dakine
class Invoices extends Eloquent {
public function payments()
{
return $this->hasMany('Payments');
}
}
class Payments extends Eloquent {
public function invoices()
{
return $this->belongsTo('Invoices');
}
}
In your controller
在您的控制器中
Invoice::with(['payments' => function($query){
$query->sum('amount');
}])->get();
;
;
回答by Hepworth
First decide which Invoice (for example id 1)
首先决定哪个发票(例如id 1)
$invoice = Invoices::find(1);
Then eager load all the corresponding payments
然后立即加载所有相应的付款
$eagerload = $invoice->payments;
Finally assuming you have the amount
field in your Invoice model you can simply find the sum using the method below:
最后假设您amount
的 Invoice 模型中有该字段,您可以使用以下方法简单地找到总和:
$totalsum = $eagerload->sum('amount');
回答by Алексей Морозов
回答by scx
I found a simple way to acomplish this in here, you can use withPivot()method.
我在这里找到了一个简单的方法来完成这个,你可以使用withPivot()方法。
You can redefine a bit your relation to something like following
您可以重新定义与以下内容的关系
public function expenses()
{
return $this->belongsToMany('Expenses', 'invoices_expenses')
->withPivot('name', 'amount', 'date');
}