Laravel Eloquent选择与关系不同

时间:2017-05-09 21:28:43

标签: mysql laravel laravel-eloquent

我在类别和产品表之间有多对多的关系。

┌─────────────────┐          ┌─────────────────┐          ┌──────────────────┐
│ 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();

我得到重复的数据。 所以我想知道如何为类别执行明确的选择?

BTW:我尝试在每个模型上添加一个范围,为查询添加了distinct,但它没有用。

2 个答案:

答案 0 :(得分:1)

除非我遗漏了某些内容,否则您应该可以使用groupBy()

$shop = Shop::find(1);
$shop->categories()->groupBy('category_id')->get();

答案 1 :(得分:-1)

$shop->categories()->distinct()->get();
相关问题