【问题标题】:Laravel Relationship Query to load hasMany + BelongsToManyLaravel 关系查询加载 hasMany + BelongsToMany
【发布时间】:2021-10-07 13:40:51
【问题描述】:

我需要在特定的collection 页面中获取brands 数据,但只有多个product

这是模型之间的关系。

Brand -> HasMany -> Product

Product <= BelongsToMany => Collection

我能够获得所有系列中包含超过 1 种产品的品牌数据,如下所示:

$brands = Brand::has("products")->get(); //this will return all brands that have more than 1 product.

现在我需要在这里添加收藏限制。

我可以从$slug 获取特定页面的收藏。

$collection = Collection::where("slug", $slug)->first();

谁能帮我如何获取特定收藏页面的品牌?

【问题讨论】:

    标签: php mysql laravel eloquent laravel-relations


    【解决方案1】:

    试试这个:

    $brands = Brand::has("products")
    ->whereHas('products.collections',function($q) use ($slug){ // your relation to product model
      $q->where("slug", $slug);
    })
    ->get();
    

    【讨论】:

    • 这太棒了!顺便说一句,没有任何n+1 查询问题吗?比如我们不需要急切加载products.collections吗?
    • 通过上面的查询,它会加入product和collection记录并根据条件过滤,它会得到记录或brand表,你可以访问product和collection表记录
    猜你喜欢
    • 2021-03-22
    • 1970-01-01
    • 2018-01-03
    • 2022-01-16
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    相关资源
    最近更新 更多