我不确定这是 Laravel 中的错误还是我做错了什么。
我有两个表clothes
和clothes_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/