【问题标题】:laravel join query return two identical ids for two different datalaravel 连接查询为两个不同的数据返回两个相同的 id
【发布时间】:2021-03-30 10:31:01
【问题描述】:

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

我有两张桌子clothesclothes_category

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

Laravel 出于某种奇怪的原因而不是返回衣服 ID。它返回了clothing_category id,因此在衣服中找到的所有数据都与衣服_category.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 会发生这种情况?

【问题讨论】:

    标签: php mysql sql laravel


    【解决方案1】:

    您正在选择所有列,因此您同时拥有来自 clothesclothes_categoryid 列。

    为您的查询添加选择

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

    【讨论】:

      【解决方案2】:

      您只需将结果按clothes 分组即可。

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

      【讨论】:

      • 虽然您的解决方案似乎是正确的。它对我不起作用,它引发了这个错误Syntax error or access violation: 1055。但是我确实找到了一个解决方案,我只需要在 join() 之前添加一个 select('clothes.*')。解决了这个问题。我仍然会赞成您的回答,因为我相信这也是解决它的一种方法。我只是无法让它在我的环境中运行。
      • 你可以通过查看stackoverflow.com/questions/40917189/…来解决这个问题
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      • 2021-12-27
      相关资源
      最近更新 更多