A while back an avg query was solved, not your exact problem but may help https://laracasts.com/discuss/channels/eloquent/orderby-computed-related-attribute?page=1
Mar 29, 2016
1
Level 3
Group by date within date range and average value
I have a fuel tank levels table that holds hourly level readings. In order to graph these levels over long periods I need to get the average of the volume recorded between a given date range.
The following works perfectly to group the hourly level readings by day:
$levels = TankLevel::where('tank_id', '=', $tank->id)
->where('level_date', '>', $start_date->format('Y-m-d H:i'))
->where('level_date', '<', $end_date->format('Y-m-d H:i'))
->get()
->groupBy(function($date) use ($site) {
return Carbon::parse($date->level_date)->setTimezone($site->site_timezone->timezone)->format('d'); }) ;
What I'm struggling with is how to add ->ave('volume') into the mix so that I get a results set that is grouped by day (or month, or year) AND which aggregates the volume value as an average. I'm not sure if what I'm trying to do is even possible. Any help would be much appreciated.
Please or to participate in this conversation.