【问题标题】:Laravel Many to Many QueryLaravel 多对多查询
【发布时间】:2017-09-30 17:50:24
【问题描述】:

所以我有一个products 表和一个categories 表和一个pivot 表。

产品 (products)

--标识

--名字

类别 (categories)

--标识

--名字

CategoryProduct (category_product)

-- category_id

--product_id

我想获取属于某个类别的所有产品,我通过执行以下查询设法得到它:

$products = Category::find(3)->products;

但是我如何才能从产品模型中访问它呢?

$products = Product::?

【问题讨论】:

    标签: laravel laravel-5 eloquent


    【解决方案1】:

    您需要whereHas 子句。 https://laravel.com/docs/5.4/eloquent-relationships#querying-relationship-existence

    $products = Product::whereHas('categories', function ($query) {
        return $query->where('id', 3);
    })->get();
    

    或者你可以用一个连接来代替。

    $products = Product::select('products.*')
        ->join('category_product', 'products.id', '=', 'category_product.product_id')
        ->where('category_product.category_id', 3)
        ->groupBy('products.id')
        ->get();
    

    【讨论】:

    • SQLSTATE[23000]:完整性约束违规:1052 where 子句中的列 'id' 不明确。那是我在运行您的代码时遇到的错误
    • 哪个 sn-p 给出了这个错误?您是否添加了任何其他子句、范围等?
    • 第一个sn-p。
    • @robertmylne 你做了什么编辑?出了什么问题?
    • 编辑因某种原因被@pang 拒绝。这返回 $query->where('id', 3);改为这个 return $query->where('category_id', 3);删除错误
    猜你喜欢
    • 2018-06-07
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 2017-07-30
    • 2020-03-11
    • 2018-11-02
    • 2015-05-29
    • 1970-01-01
    相关资源
    最近更新 更多