php - laravel join 查询为两个不同的数据返回两个相同的 id

标签 php mysql sql laravel

我不确定这是 Laravel 中的错误还是我做错了什么。

我有两个表clothesclothes_category

我的SQL非常简单,我从衣服中选择所有内容并加入衣服类别,其中衣服.category_id与衣服类别.id映射。这应该只返回已映射到 dress_categor.id 的衣服。简单又容易。

Laravel 由于某些奇怪的原因而不是返回衣服 ID。它返回衣服类别ID,因此在衣服中找到的所有数据都与衣服类别ID一起返回。

返回数据:

[
{
  "id":1,
  "name":"clothes 1", NOTICE this shows that the clothes data is actually different
  "category_id":1,
  "category":"hoodie",
},
{
  "id":1,
  "name":"clothes10", NOTICE this shows that the clothes data is actually different
  "category_id":1,
  "category":"hoodie",
}
]

Laravel 查询

return Clothes::join('clothes_category', 'clothes_category.id', '=', 'clothes.category_id')
            ->where('clothes_category.category', $cat)->get();

使用普通 SQL:

SELECT *
FROM clothes
INNER JOIN clothes_category ON clothes_category.id = clothes.category_id
WHERE clothes_category.category = 'hoodie';

[
{
  "id":1, NOTICE id is different now
  "name":"clothes 1", 
  "category_id":1,
  "category":"hoodie",
},
{
  "id":2, NOTICE id is different now
  "name":"clothes10", 
  "category_id":1,
  "category":"hoodie",
}
]

我不明白为什么会发生这种情况。有谁知道为什么使用 laravel 会发生这种情况?

最佳答案

您只需按衣服对结果进行分组即可。

return Clothes::join('clothes_category', 'clothes_category.id', '=', 'clothes.category_id')
            ->where('clothes_category.category', $cat)
            ->groupBy('clothes.id')
            ->get();

关于php - laravel join 查询为两个不同的数据返回两个相同的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65379579/

相关文章:

php - Kohana v3,自动转义非法字符?

用于存储多种语言的 MySQL 编码

sql - 将数据类型 varchar 转换为 bigint 时出错

php - 使用 php 运行 cron 作业时出现错误,我该如何解决?

PHP Regex - 删除多余的空格但保留换行符

php - Symfony生产模式错误报告和P​​OST值

mysql - CakePHP 发送多封电子邮件而不是一封

Python Django : displaying special characters in admin, 但不在我的网站上?

sql - 为什么我读到这么多关于使用复合键的负面意见?

sql - Oracle——优化SQL查询