Laravel 在连接结果上不同,在查询生成器中不起作用
Posted
技术标签:
【中文标题】Laravel 在连接结果上不同,在查询生成器中不起作用【英文标题】:Laravel distinct on join results not working in query builder 【发布时间】:2018-09-13 02:41:13 【问题描述】:我有一个帖子表,其中包含与其他 4 个表的连接查询。其中 3 个是一对一的关系,而第 4 个是一对多的。我希望查询为每个帖子只返回 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 个帖子,但查询返回每个帖子图像的所有行,每个帖子超过 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();
奇怪的是laravel显示的SQL查询“ select posts
.*, postimages
.postimage_thumbnail
from posts
inner join postimages
on postimages
.post_id
= @987654330 @.post_id
group by posts
.post_id
" 在 mysql 中工作正常
【问题讨论】:
您想获得哪一行postimages
? id
最低的那个?
这样最好。
在有人发布雄辩的方式之前,我现在确实在运行,这对于成为查询构建器很重要。
【参考方案1】:
你应该使用 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');
在“mysql”处的 config/database.php 中更改:'strict' => true, to false
【讨论】:
一些奇怪的错误 - 它说 SQLSTATE[42000]: Syntax error or access violation: 1055 'db_ibikri.posts.user_id' is not in GROUP BY (.... 在“mysql”处的 config/database.php 中更改:'strict' => true,为 false。希望对您有所帮助! 好的,现在错误消失了,但它选择了 post_id = 1 的所有图像,我如何让它选择所有 post_ids 中的第一个? 等一下,我认为已经解决了。我只需要使用 groupBy('postimages.post_id') 非常感谢。我坚持了这么久 我编辑了答案以包括将 mysql strict 更改为 false 的部分。再次感谢您。以上是关于Laravel 在连接结果上不同,在查询生成器中不起作用的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Laravel Eloquent 在不同服务器上的多个数据库之间执行连接查询?
使用 Laravel Query Builder 进行复杂的 MySQL 内连接查询