Har*_*ist 1 sum relation laravel laravel-4
我想从我的付款表中返回“金额”的总和。一张发票可以有多次付款。下面的“->sum('amount') 不起作用,它返回:
对非对象调用成员函数 addEagerConstraints()。
如何返回我的关系中每张发票的所有付款总额?
发票型号:
class Invoices extends Eloquent {
public function payments()
{
return $this->hasMany('Payments')->sum('amount');
}
}
Run Code Online (Sandbox Code Playgroud)
费用模型:
class Payments extends Eloquent {
public function invoices()
{
return $this->belongsTo('Invoices');
}
}
Run Code Online (Sandbox Code Playgroud)
我的表“付款”保存表发票的外键,即invoices_id。
Jak*_*mec 13
从Laravel 8开始,您可以简单地使用withSum()函数。
use App\Models\Post;
$posts = Post::withSum('comments', 'votes')->get();
foreach ($posts as $post) {
echo $post->comments_sum_votes;
}
Run Code Online (Sandbox Code Playgroud)
https://laravel.com/docs/8.x/eloquent-relationships#other-aggregate-functions
class Invoices extends Eloquent {
public function payments()
{
return $this->hasMany('Payments');
}
}
class Payments extends Eloquent {
public function invoices()
{
return $this->belongsTo('Invoices');
}
}
Run Code Online (Sandbox Code Playgroud)
在你的控制器中
Invoice::with(['payments' => function($query){
$query->sum('amount');
}])->get();
Run Code Online (Sandbox Code Playgroud)
;