Laravel distinct on join 结果在查询生成器中不起作用

Laravel distinct on join results not working in query builder

我有一个 posts table 与其他 4 个 tables 有连接查询。其中 3 个是一对一关系,但第 4 个是一对多关系。我希望查询 return 每个 post 只有 1 行。到目前为止我正在尝试的是这样的-

$query = DB::table('posts')
                ->select('posts.*',
                        'subcategories.subcategory_title_en',
                        'subcategories.subcategory_title_bn',
                        'categories.category_title_en',
                        'categories.category_title_bn',
                        'users.*',
                        'postimages.postimage_thumbnail'
                        )
                ->join('subcategories', 'subcategories.subcategory_id', '=', 'posts.subcategory_id')
                ->join('categories', 'categories.category_id', '=', 'subcategories.parent_category_id')
                ->join('users', 'users.id', '=', 'posts.user_id')
                ->join('postimages', 'postimages.post_id', '=', 'posts.post_id');

        $query->groupBy('posts.post_id');

        echo $query->count();
        exit();

我目前在数据库中有 50 posts,但是查询 returns 每个 post 图像的所有行,每个 post 超过 1 行是。我以为 distinct 只会显示每个 post_id 一次?我在这里错过了什么?

如果有人告诉我如何使用查询生成器执行此操作,我会更愿意。因为这将在不同的列上进行大量搜索,所以我希望它尽可能快。

这是一个更简单的版本 -

 $query = DB::table('posts')
                ->select('posts.*','postimages.postimage_thumbnail')
                ->join('postimages', 'postimages.post_id', '=', 'posts.post_id')
                ->groupBy('posts.post_id');


        echo $query->count();
        exit();

奇怪的是 SQL 查询显示为 laravel " select posts.*, postimages.postimage_thumbnailposts 内部加入 postimagespostimages.post_id = posts.post_idposts.post_id 分组" 在 mysql

中工作正常

你应该使用 groupby

试试这个代码

 $query = DB::table('posts')
            ->select('posts.*',
                    'subcategories.subcategory_title_en',
                    'subcategories.subcategory_title_bn',
                    'categories.category_title_en',
                    'categories.category_title_bn',
                    'users.*',
                    'postimages.postimage_thumbnail'
                    )
            ->join('subcategories', 'subcategories.subcategory_id', '=', 'posts.subcategory_id')
            ->join('categories', 'categories.category_id', '=', 'subcategories.parent_category_id')
            ->join('users', 'users.id', '=', 'posts.user_id')
            ->join('postimages', 'postimages.post_id', '=', 'posts.post_id')->groupBy('posts.post_id');

在 config/database.php 中 "mysql" 更改:'strict' => true,为 false