filippo-toso / eloquent-aggregates
一个简单的特质,用于在 Eloquent 模型中添加对聚合函数的支持
v1.0.2
2021-09-25 08:06 UTC
Requires
- php: ^7.0 || ^8.0 || ^9.0
- illuminate/support: >=5.7
- laravel/helpers: ^1.1
This package is auto-updated.
Last update: 2024-09-25 14:17:52 UTC
README
一个简单的特质,用于在 Eloquent 模型中添加对聚合函数的支持。
要求
- PHP 7.2+
- Laravel 5.7+
安装
使用 Composer 安装
composer require filippo-toso/eloquent-aggregates
如何使用它
将 FilippoToso\Eloquent\Aggregates\Concerns\HasAggregates 特质添加到您的模型中。然后您可以使用以下方法
// Get the sum of all the amount fields in the transactions relationship
$users = App\Users::withSum('amount', 'transactions')->get();
// Get the max of all the amount fields in the transactions relationship
$users = App\Users::withMax('amount', 'transactions')->get();
// Get the min of all the amount fields in the transactions relationship
$users = App\Users::withMin('amount', 'transactions')->get();
// Get the average of all the amount fields in the transactions relationship
$users = App\Users::withAvg('amount', 'transactions')->get();
您还可以添加约束到关系查询
$users = App\Users::withAvg('amount', ['transactions' => function ($query) {
// Include only the transaction created in the last seven days
$query->whereDate('created_at', '>=', Carbon\Carbon::today()->subDays(7));
}])->get();
已经扩展了 Eloquent Builder 吗?
如果您已经扩展了 Illuminate\Database\Eloquent\Builder,只需将特质 FilippoToso\Eloquent\Aggregates\Concerns\QueriesAggregates 添加到您的 Builder 类中。