-
Notifications
You must be signed in to change notification settings - Fork 11.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[8.x] Add loadAggregate() and load[min(), max(), sum() & avg()] methods to … #35029
Conversation
…Eloquent/{Collection, Model} Also add loadMorphAggregate() and loadMorph[min(), max(), sum() & avg()] methods to Eloquent/Model
Will it be possible to load multiple relations at once? Maybe even with constraints? Such as: $orders->loadSum([
'orderItems.price as original_total_cost',
'orderItems.weight as shipping_weight',
'orderItems.price as total_refunded' => function($query) {
$query->where('is_refunded', true);
},
]) |
@dbakan Yes, it is possible. Just you forgot to specify the second argument (the |
@khalilst I specified different columns intentionally as part of the array keys/relation names: To me, this would be closer to the "Laravel Way", esp. if all aggregates are being fetched within a single statement. |
@dbakan It needs to change the source |
@khalilst I'd be happy to help with those changes. |
@khalilst This is an approach I've been working on lately: https://github.com/dbakan/aggregate It does not work for the current 8.x, but it does work for v8.11.2 (before the new It supports the dot syntax, mixed constraints and some more. It's still work in progress and has some issues, but personally, I prefer: Order::withSum('products.price as total');
// over
Order::withSum('products as total', 'price'); And I think this would be more flexible, e.g. mix aggregates: Order::withAggregate([
'products as products_count' => 'count',
'products.deleted_at AS deleted_count' => 'count',
'products.quantity as total_items' => 'sum', // using sum() here now!
'products.price as special_aggregate' => function($query) {
// write more complex aggregates:
$query->select(\DB::raw('SUM(product_orders.quantity*product_orders.price)'));
},
'products.discount' => 'MAX',
'products.quantity as quantity_list' => 'group_concat', // (I am working on JSON_ARRAY_AGGR too)
]); What do you think @khalilst @taylorotwell ? |
@dbakan I disagree with all respect. If I was there to make Model::withCount($relations, $alias) instead of Medel::withCount('relation as alias'); But if others and @taylorotwell have your idea I will make another PR for these changes with your help. |
@khalilst Yes, this may be true. I just liked the idea of supporting multiple aggregates over different columns like: Model::loadSum(
'relation.price AS total_cost',
'relation.weight AS total_weight',
...
); And doing it in a single query just like |
This PR adds the following methods to the
Eloquent/{Collection, Model}
which were missing in PR #34965:And