mardi 20 novembre 2018

I have a value 'marks' in a pivot table, how to find student rank based on 'marks' value using query builder?

I have two models Exam and Student, after every student attempts an Exam that marks obtained by her/him is stored in the pivot table exam_user. I need to rank the student based on the marks obtained.

Right now I am using a very inefficient solution for this, which involves a for-loop. Below is the implementation

            $rank=0;
            $attempts = DB::table('exam_user')
                    ->where('exam_id',$exam->id)
                    ->orderBy('marks','desc')
                    ->get();
            foreach ($attempts as $attempt) {
                $rank++;
                if($attempt->user_id==Auth::id())
                    break;
            }

Is there any way I can determine the rank without using a for loop, simply using the query builder in laravel. I think I am missing some SQL fundamentals here.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire