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

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

Laravel Sum of relation

laravellaravel-4sumrelation

提问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 amountfield in your Invoice model you can simply find the sum using the method below:

最后假设您amount的 Invoice 模型中有该字段,您可以使用以下方法简单地找到总和:

$totalsum = $eagerload->sum('amount');

回答by Алексей Морозов

You can show this package

你可以展示这个

$invoices = Invoices::withSum('payments:amount')->get();

回答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');
}