Mysql 如何在我的情况下正确使用查询生成器Laravel?

Mysql 如何在我的情况下正确使用查询生成器Laravel?,mysql,sql,laravel,Mysql,Sql,Laravel,我有一部分SQL代码需要为查询生成器(Laravel)正确转换 有人能拦住我吗/ 使用查询生成器,您可以将其编写为 $posts = DB::table('posts as p') ->join('comments as c', 'p.post_id', '=', 'c.post_id') ->groupBy('p.post_id') ->orderByRaw('avg(c.mark_first) desc

我有一部分SQL代码需要为查询生成器(Laravel)正确转换


有人能拦住我吗/

使用查询生成器,您可以将其编写为

$posts = DB::table('posts as p')
            ->join('comments as c', 'p.post_id', '=', 'c.post_id')
            ->groupBy('p.post_id')
            ->orderByRaw('avg(c.mark_first) desc')
            ->select('p.*')
            ->get();
如果可以在
select
部分中添加所需的
groupby
中的所有列,则效果会更好,因为如果启用了mysql的
full\u group\u by
模式(默认情况下在5.7+中启用),则上述查询将无效

$posts = DB::table('posts as p')
            ->join('comments as c', 'p.post_id', '=', 'c.post_id')
            ->groupBy('p.post_id')
            ->orderByRaw('avg(c.mark_first) desc')
            ->select('p.*')
            ->get();