watson / aggregate
扩展Laravel查询构建器的附加关系聚合。
5.2.0
2024-03-01 22:39 UTC
Requires
- php: ^8.1
- illuminate/database: ^10.0|^11.0
Requires (Dev)
- mockery/mockery: ^1.4.4
- orchestra/testbench: ^8.0|^9.0
- phpunit/phpunit: ^9.5.10|^10.5
README
Laravel Eloquent 允许您使用 withCount
查询关系的数量。Aggregate 通过添加 withSum
、withAvg
、withMin
和 withMax
扩展了 Eloquent。
这基于 laravel/framework#25319
的工作 - 感谢 Mohammad Sharif Ahrari (@spyp)。
安装
您可以通过 Composer 安装此包
composer require watson/aggregate
用法
额外的方法将通过 Laravel 的自动发现功能添加。然后,您可以像使用 withCount
一样使用它们。有关更多信息,请参阅 Laravel 文档。
$orders = Order::withSum('products', 'quantity')->get(); $orders->each(function ($order) { $order->products_sum; });
您还可以在单个查询中同时选择多个聚合,并为其指定别名。
$orders = Order::withCount('products')->withSum('products as products_price', 'price')->get(); $orders->each(function ($order) { $order->products_count; $order->products_price; });
$orders = Order::withCount('products')->withMax('products', 'price')->get(); $orders->each(function ($order) { $order->products_count; $order->products_max; });
测试
vendor/bin/phpunit