php - Laravel sql take top records and get it's field values average -


how can able top records e.g top 10 top 5 top 3, i've tried use avg on query returns whole average of persons record.

sql

if( !$field ) {     $select = [         db::raw('avg(sfieldgoalspercentage) sfieldgoalspercentage'),          db::raw('avg(sthreepointerspercentage) sthreepointerspercentage'),          db::raw('avg(stwopointerspercentage) stwopointerspercentage')     ]; }  $player1 = db::table('person_match_statistics')     ->where('competitionid', $competitionid)     ->where('personid', $player1id)     ->where('periodnumber', 0)     ->orderby('matchid', 'desc')     ->select($select)     ->take($lastgame)     ->get(); 

array

0 => {#543 ▼   +"sfieldgoalspercentage": 0.56   +"sthreepointerspercentage": 0.5   +"stwopointerspercentage": 0.63 } 1 => {#536 ▼   +"sfieldgoalspercentage": 0.4   +"sthreepointerspercentage": 0.4   +"stwopointerspercentage": 0.4 } 2 => {#539 ▼   +"sfieldgoalspercentage": 0.38   +"sthreepointerspercentage": 0.2   +"stwopointerspercentage": 0.67 } 

you use avg() collection method. top ten records:

$player1 = db::table('person_match_statistics')     ->where('competitionid', $competitionid)     ->where('personid', $player1id)     ->where('periodnumber', 0)     ->latest('matchid')     ->select($select)     ->take(10)     ->get(); 

then count average without executing new queries using take() , avg() collection methods. example:

$top10 = $player1->avg('column'); $top5 = $player1->take(5)->avg('column'); $top3 = $player1->take(3)->avg('column'); 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -