我在类别和产品表之间建立了多对多关系。
┌─────────────────┐ ┌─────────────────┐ ┌──────────────────┐
│ categories │ │ products │ │ category_product │
├─────────────────┤ ├─────────────────┤ ├──────────────────┤
| id | | id | | shop_id |
| name | | name | | category_id |
| created_at | | price | | product_id |
└─────────────────┘ | created_at | | created_at |
└─────────────────┘ └──────────────────┘
类别模型:
class Category extends Model
{
public function products()
{
return $this->belongsToMany(Product::class);
}
}
产品型号:
class Product extends Model
{
public function categories()
{
return $this->belongsToMany(Category::class);
}
}
因为我还使用 cetegory_product 表来映射商店。我在获得不同的结果时遇到了一些问题。假设我在数据透视表中有以下记录:
shop_id | category_id | product_id
--------------------------------------
1 |18 |4
1 |18 |5
现在,当我尝试获取商店的类别或像这样的反向关系时:
$shop = Shop::find(1);
$shop->categories()->get();
我得到了重复的数据。 所以我想知道如何对类别执行不同的选择?
顺便说一句:我试图在每个模型上添加一个范围,将不同的添加到查询中,但它没有用。
最佳答案
除非我遗漏了一些你应该能够使用 groupBy()
的东西。
$shop = Shop::find(1);
$shop->categories()->groupBy('category_id')->get();
关于mysql - Laravel Eloquent 选择区别于关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43880152/