我想要返回"金额"的总和从我的付款表。一张发票可以有很多付款。以下" - >总和('金额')不起作用,它返回:
在非对象上调用成员函数addEagerConstraints()。
如何返回我关系中每张发票的所有付款总额?
发票型号:
class Invoices extends Eloquent {
public function payments()
{
return $this->hasMany('Payments')->sum('amount');
}
}
费用模型:
class Payments extends Eloquent {
public function invoices()
{
return $this->belongsTo('Invoices');
}
}
我的表"付款"保存我的表发票的外键,即invoices_id。
答案 0 :(得分:2)
这也是可能的。我们可以通过模型本身来完成。
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)
付款是tableName
数量是fieldName
答案 1 :(得分:1)
我找到了一种在here中完成此操作的简单方法,您可以使用withPivot()方法。
您可以将您的关系重新定义为以下内容
public function expenses()
{
return $this->belongsToMany('Expenses', 'invoices_expenses')
->withPivot('name', 'amount', 'date');
}
答案 2 :(得分:1)
首先确定哪个发票(例如id 1)
$invoice = Invoices::find(1);
然后急切加载所有相应的付款
$eagerload = $invoice->payments;
最后假设您的发票模型中有amount
字段,您只需使用以下方法查找总和:
$totalsum = $eagerload->sum('amount');
答案 3 :(得分:1)
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();
答案 4 :(得分:1)
您可以显示此package
$invoices = Invoices::withSum('payments:amount')->get();
答案 5 :(得分:1)
从 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