mysql - Laravel Eloquent 选择区别于关系

标签 mysql 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();

我得到了重复的数据。 所以我想知道如何对类别执行不同的选择?

顺便说一句:我试图在每个模型上添加一个范围,将不同的添加到查询中,但它没有用。

最佳答案

除非我遗漏了一些你应该能够使用 groupBy() 的东西。

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

关于mysql - Laravel Eloquent 选择区别于关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43880152/

相关文章:

laravel - 查询未正确执行

php - Eloquent中如何使用基于ORDER BY子句的LIMIT查询

php - 如果不在 url 上添加 index.php,laravel 5.2 项目将无法运行

php - Laravel 5 资源链接

php - 413请求实体太大

mysql - MySQL 中有没有办法在二进制列的子部分中使用聚合函数?

laravel - 数据正在插入数据库但显示错误

mysql - 重写 SQL 查询以在 heroku 上工作

Mysql if语句选择多行

mysql - 优化更新查询功能,可异步更新1000条以上记录