Laravel Collection Macro Filter by Today



我有以下场景:

  1. 一个业务表,其模型的事务如下:
public function transactions(): HasMany {
return $this->hasMany(Transaction::class);
}
  1. 事务表(事务属于业务(-具有id、amount和timestamp列

我在刀片服务器视图中显示所有业务及其交易计数和价值。现在我想按今天的日期过滤交易计数和价值。我已经看到最好的方法是做一个集合宏。以下是到目前为止我在应用程序服务提供商(不起作用(中所做的:

Collection::macro('filterByToday', function ($value) {
return $this->filter(function ($value) {
return $value->created_at === Carbon::today(); 
});
});

我如何编写这个宏,以便在blade中循环浏览显示此事务的所有业务,如:

@foreach($businesses as $business)
Count: {{ $business->transaction->filterByToday()->count() }}
Value: {{ $business->transaction->filterByToday()->sum('amount') }}
@endforeach

宏不应接收任何参数,并且应在ServiceProvider类的boot方法中定义。

如果您使用的是自定义ServiceProvider类,请确保它已在config/app.php$providers数组中注册

# AppServiceProvider
public function boot()
{
Collection::macro('filterByToday', function () { // <-- 0 arguments
return $this->filter(function ($value) {
return $value->created_at === Carbon::today(); 
});
});
}

最新更新