使用Laravel中的groupby选择最新一行


Selecting the latest row using groupby in Laravel

我有一个类似于以下的表条目:

+---------+---------+----------+
| 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 BYGROUP BY不能很好地协同工作。。。

如果你只是想要每个test_id的最高尝试,我建议使用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();

您可以使用以下行:

 Testresult::select('*')
         ->join(DB::raw('(Select max(id) as last_id from Testresult group by test_id) LatestId'), function($join) {
            $join->on('Testresult.id', '=', 'LatestId.last_id');
            })
         ->orderBy('attempts', 'desc');
}