Eloquent查询获取数据库中的最高和第二高值

问题描述 投票:0回答:1

This is the image of my dattabase

我有一个Laravel Eloquent的问题,要从主题组='E1'的'student_number'中获取具有最高值和第二高值的主题名称。这是我尝试过但它包含一个错误“max():当只给出一个参数时,它必须是一个数组”并且我不知道如何获得'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'));
}
laravel-5 eloquent laravel-5.5
1个回答
0
投票
FinalyearSubject::where('subject_group', 'E1')
->orderBy('student_number', 'DESC')
->limit(2)
->get()

说明:

  • 添加过滤器
  • 按student_number降序排序
  • 进入前2名
  • get()结果

你正在做FinalyearSubject::get()的那一刻,查询已经完成了。 get()返回一个Collection对象(更像是一个丰富的数组)。之后链接的所有内容都是使用Laravel的Collection实用程序计算的。 ->get()通常应该是你调用中的最后一件事,这样你就可以在SQL中做尽可能多的工作。

© www.soinside.com 2019 - 2024. All rights reserved.