Laravel 关系之和

Laravel Sum of relation

我想从我的付款 table 中提取 "amount" 的总和。一张发票可以有很多付款。下面的 "->sum('amount') 不起作用,它 returns:

在非对象上调用成员函数 addEagerConstraints()。

如何return我关系中每张发票的所有付款总和?

发票模型:

class Invoices extends Eloquent {

    public function payments()
    {
        return $this->hasMany('Payments')->sum('amount');
    }
}

费用模型:

class Payments extends Eloquent {

    public function invoices()
    {
        return $this->belongsTo('Invoices');
    } 
}

我的 table "payments" 持有我的 table 发票的外键,即 invoices_id。

我在 here, you can use withPivot() 方法中找到了完成此操作的简单方法。

您可以稍微定义一下您与以下内容的关系

public function expenses()
{
    return $this->belongsToMany('Expenses', 'invoices_expenses')
                   ->withPivot('name', 'amount', 'date');
} 

首先决定哪个发票(例如id 1)

$invoice = Invoices::find(1);

然后预加载所有相应的付款

$eagerload = $invoice->payments;

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

$totalsum = $eagerload->sum('amount');
class Invoices extends Eloquent {

    public function payments()
    {
        return $this->hasMany('Payments');
    }
}

class Payments extends Eloquent {

    public function invoices()
    {
        return $this->belongsTo('Invoices');
    } 
}

在你的控制器中

Invoice::with(['payments' => function($query){
   $query->sum('amount');
}])->get();

;

你可以展示这个package

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

这也是可以的。我们可以通过模型本身来做。

class Invoices extends Eloquent {

    public function payments()
    {
        return $this->hasMany('Payments')
            ->selectRaw('SUM(payments.amount) as payment_amount')
            ->groupBy('id'); // as per our requirements.
        }
    }
}

备注 SUM(payments.amount)

payments is tableName

amount is fieldName

Laravel 8 开始,您可以简单地使用 withSum() 功能。

use App\Models\Post;

$posts = Post::withSum('comments', 'votes')->get();

foreach ($posts as $post) {
    echo $post->comments_sum_votes;
}

https://laravel.com/docs/8.x/eloquent-relationships#other-aggregate-functions