Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/dwightwatson/aggregate
Support additional aggregate queries on Eloquent relations
https://github.com/dwightwatson/aggregate
eloquent laravel php
Last synced: about 18 hours ago
JSON representation
Support additional aggregate queries on Eloquent relations
- Host: GitHub
- URL: https://github.com/dwightwatson/aggregate
- Owner: dwightwatson
- License: mit
- Created: 2018-09-17T04:56:12.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2024-03-13T02:17:27.000Z (8 months ago)
- Last Synced: 2024-04-14T06:06:56.436Z (7 months ago)
- Topics: eloquent, laravel, php
- Language: PHP
- Size: 12.7 KB
- Stars: 62
- Watchers: 4
- Forks: 10
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# Aggregate
Laravel Eloquent allows you to query the count of a relationship using `withCount`. Aggregate extends Eloquent by adding `withSum`, `withAvg`, `withMin` and `withMax`.
This is based off the work in [`laravel/framework#25319`](https://github.com/laravel/framework/pull/25319) - thanks to Mohammad Sharif Ahrari ([@spyp](https://github.com/spyp)).
## Installation
You can install the package via Composer:
```bash
composer require watson/aggregate
```## Usage
The additional methods will be added by Laravel's autodiscovery feature. You can then use them the same way you already use `withCount`. [See the Laravel documentation for more on how this works](https://laravel.com/docs/5.7/eloquent-relationships#counting-related-models).
```php
$orders = Order::withSum('products', 'quantity')->get();$orders->each(function ($order) {
$order->products_sum;
});
```You can also select multiple aggregates in a single query, as well as alias them.
```php
$orders = Order::withCount('products')->withSum('products as products_price', 'price')->get();$orders->each(function ($order) {
$order->products_count;$order->products_price;
});
``````php
$orders = Order::withCount('products')->withMax('products', 'price')->get();$orders->each(function ($order) {
$order->products_count;$order->products_max;
});
```### Testing
``` bash
vendor/bin/phpunit
```