Laravel关系的总和

Laravel关系的总和

本文介绍了Laravel关系的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的付款表中返回金额"的总和.一张发票可以有很多付款.下面的-> sum('amount')无效,返回:

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:

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

Call to a member function addEagerConstraints() on a non-object.

如何返回我关系中每张发票的所有付款之和?

How to return the sum of all payments for each invoice in my relation?

发票模型:

class Invoices extends Eloquent {

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

费用模式:

class Payments extends Eloquent {

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

我的表"payments"保存我的表发票的外键,即invoices_id.

My table "payments" holds the foreign key of my tables invoices, which is invoices_id.

推荐答案

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();

;

这篇关于Laravel关系的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:57