1

i'm trying to get all measurements from a certain recorder between a certain timespan.
If i remove the "->wherebetween()" part of the query and view the results then I get all the sensors of that recorder and all related measurements of that sensor.
But I'm not able to execute a wherebetween on the relation.

query in the controller

public function getChart(Request $request) {
    $sensorCollection = Sensor::where('recorder_id', $request->recorder_id)
        ->with('getMeasurementsRelation')
        ->wherebetween('getMeasurementsRelation', function ($query) use ($request) {
            return $query->wherebetween('timestamp',[$request->start_chart, $request->end_chart]);})
            ->get();
}

Relationship in Sensor model

public function getMeasurementsRelation() {
        return $this->hasmany('App\Models\measurement', 'sensor_id', 'id');}
vennot_be
  • 17
  • 4

1 Answers1

1

You can use callback in with method like below.Since you have not mentioned start and end chart value format .So i assume its Y-m-d format .if not let me know in comment i can modify my answer according to your need

$sensorCollection = Sensor::where('recorder_id', $request->recorder_id)
        ->with(['getMeasurementsRelation'=>function($query)use($request){
            $startChart=\Carbon\Carbon::createFromFormat('Y-m-d',$request->start_chart)->startOfDay();

            $endChart=\Carbon\Carbon::createFromFormat('Y-m-d',$request->end_chart)->endOfDay();

            $query->wherebetween('timestamp',[$startChart, $endChart]);
        }])

        ->get();
vennot_be
  • 17
  • 4
John Lobo
  • 14,355
  • 2
  • 10
  • 20
  • It worked, thanks!!! I've added "->startOfDay ()" and "->endOfDay ()" to format the time to fixed point. Without this extra formatting I would get different starting en ending points based upon the time(H:m:s) that you searched. – vennot_be May 30 '21 at 12:18
  • @vennot_be.okay glad that you solved your issue – John Lobo May 30 '21 at 12:18