Home > Software engineering >  Get latest value in the group of records
Get latest value in the group of records

Time:06-16

I have this records table which I save weight, age and other biometrics in it. Now I want to fetch the latest value of every biometric for every day so I can draw a chart. The piece of code I'm using to fetch data from db before processing it is like the following:

 Records::where("user",$uid)->
     where("type", "biometric" )->  // record type
     where("fk", $bid )->    //biometric type
     where("datetime","<" ,$range->max)->
     where("datetime",">" ,$range->min)->
     groupBy( "datee" )->
     selectRaw("  max(amount)  as 'damount' , max(unit) as 'unit' ,   date(datetime) as 'datee'  ")->
     orderBy("datee","desc")->
     get(); 
    // !! Should change max values with the latest record in the group !!

Which datee is date of the day. Say some users add more than one weight biometrics in a day so unit and damount should be the unit and value of lastest record of that day.

What can I use instead of max() to achieve this?

Thanks in advance,

CodePudding user response:

Can you try this

Records::where("user",$uid)
->where("type", "biometric")
->where("fk", $bid)  
->where("datetime","<" ,$range->max)
->where("datetime",">" ,$range->min)
->latest()
->groupBy('datetime')
->get();

CodePudding user response:

Hope this helps:

Records::where("user",$uid)
    ->where(["type" => "biometric", "fk" => $bid])
    ->whereBetween(DB::raw("DATE('datetime')"), array($range->max, $range->min))
    ->groupBy("datetime")->latest()->get();
  • Related