Reputation: 45
I have a problem with Laravel Eloquent to get the subject name with the highest value and second highest value from the 'student_number' where the subject group = 'E1'. This is what I have tried but it contains an error "max(): When only one parameter is given, it must be an array" and I don't know how to get the 2nd highest value of 'student_number'.
public function electiveGroup(){
$E1 = FinalyearSubject::get()
->where('subject_group','=','E1')
->orWhere('student_number','=',max('student_number'));
return view ('admin.elective')->with(compact('E1'));
}
Upvotes: 0
Views: 4144
Reputation: 7571
FinalyearSubject::where('subject_group', 'E1')
->orderBy('student_number', 'DESC')
->limit(2)
->get()
Explanation:
get()
the resultIn your example, the moment you are doing FinalyearSubject::get()
, the query is already done. get()
returns a Collection
object (more like an enriched array). Everything you chain afterwards is calculated using Laravel's Collection utilities. ->get()
usually should be the last thing in your call so that you can do as much work in SQL as possible.
Upvotes: 1
Reputation: 129
So, Question is you want maximum of all and 2nd maximum of subject group = 'E1'.
Max of all
FinalyearSubject::where('subject_group','E1')
->max('student_number');
2nd max of 'E1'
FinalyearSubject::where('subject_group','E1')
->OrderBy('student_number','desc')
->offset(1)
->limit(1)
->get();
Upvotes: 1