How to add related aggregate data in Laravel Eloquent?
23:49 30 Jul 2019

One Metric model has many Measurements.

I've set up the relationship so I can do things like:

$metrics = Metric::with('measurements' => function($query) {
   return $query->where('timestamp', '>=', '20190731');
});

This works to fetch all the measurements from 31 July 2019 for the metrics.

But what I want to achieve now is to fetch aggregated measurement data.

EDIT: Here's a better explanation of what I'm after

If the above gives something like:

results = [
  {          id: 1,
           name: 'Metric 1',
   measurements: [
        { id: 123, metric_id: 1, value: 4,  timestamp: 2019-07-31T09:00 },
        { id: 124, metric_id: 1, value: 10, timestamp: 2019-07-31T10:00 },
        ...
        { id: 124, metric_id: 1, value: 10, timestamp: 2019-08-01T09:00 },
                 ] },
  ...
]

Then what I want to achieve would result in this:;

results = [
  {          id: 1,
           name: 'Metric 1',
   measurementStats: [
        { metric_id: 1, period: 2019-07-31, min: 4, max: 10 },
        { metric_id: 1, period: 2019-08-01, min: 10, max: 10 },
                 ] },
  ...
]

I imagine that when eager loading, Eloquent should run something like this:

  SELECT metric_id,
         DATE_FORMAT(timestamp, '%Y%m%d') as period,
         MIN(value) AS min,
         MAX(value) AS max
    FROM measurements
   WHERE metric_id IN (...)
GROUP BY metric_id, DATE_FORMAT(timestamp, '%Y%m%d')

Is there a way to achieve that in Eloquent/Laravel query builder? (Laravel 5.8)

sql laravel laravel-5 eloquent