我有一个类似的表条目,如下所示:
+---------+---------+----------+
| Test_id | User_id | Attempts |
+---------+---------+----------+
| 12 | 5 | 1 |
| 13 | 5 | 1 |
| 12 | 5 | 2 |
+---------+---------+----------+
现在我想通过
test_id
选择元素组,并且应该得到最新的条目。我试过这个问题:
$tests_took = Testresult::where('course_id', $courseId)
->where('user_id', Auth::id())
->groupby('test_id')
->orderBy('attempts', 'desc')
->get();
当我显示结果时,我只得到前两行(一个test-id只有一行-我想要这个)但是它不是test-id=12的最后一行,而是显示第一行。我总是想展示最大的尝试。
我的电流输出如下:
| 12 | 5 | 1 |
| 13 | 5 | 1 |
但我想要这个:
| 12 | 5 | 2 |
| 13 | 5 | 1 |
我怎样才能做到这一点?要在使用groupby时将最新的行作为第一个数组元素,或者有其他方法可以这样做吗?
最佳答案
ORDER BY
和GROUP BY
一起工作不太好…
如果您只希望每个测试的最高尝试次数,我建议使用MAX()
函数:
$tests_took = Testresult::select('test_id', 'user_id', DB::raw('MAX(attempts) AS max_attempts'))
->where('course_id', $courseId)
->where('user_id', Auth::id())
->groupby('test_id')
->get();