Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel how to return a whole item data with the highest value

How can I return the whole item data, I've used max to get the hieghest value but it only returns the value of the field not the whole item

public static function getTeamLeaders($competitionId, $teamId) {
        if($teamId){
            $ppg = self::where('competitionId', $competitionId)
                    ->where('teamId', $teamId)
                    ->get()
                    ->max('Points');

            $apg = self::where('competitionId', $competitionId)
                    ->where('teamId', $teamId)
                    ->get()
                    ->max('Assists');

            $fgpg = self::where('competitionId', $competitionId)
                    ->where('teamId', $teamId)
                    ->get()
                    ->max('FieldGoals');

            $data = ['ppg' => $ppg, 'apg' => $apg, 'fgpg' => $fgpg];
            return $data;
        }
    }

Result:

array:3 [▼
  "ppg" => 15.18
  "apg" => 3.76
  "fgpg" => 12.04
]
like image 346
PenAndPapers Avatar asked Oct 29 '25 18:10

PenAndPapers


1 Answers

You can use orderBy to sort on the field that you want the max of, and then select the first result.

docs: https://laravel.com/docs/5.4/queries#ordering-grouping-limit-and-offset https://laravel.com/docs/5.4/queries#retrieving-results

$ppg = self::where('competitionId', $competitionId)
                ->where('teamId', $teamId)
                ->orderBy('Points', 'desc')
                ->first();
like image 108
Teun Avatar answered Nov 01 '25 07:11

Teun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!