Laravel 关系查询加载 hasMany + BelongsToMany

Posted

技术标签:

【中文标题】Laravel 关系查询加载 hasMany + BelongsToMany【英文标题】:Laravel Relationship Query to load 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();

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

【问题讨论】:

【参考方案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表记录

以上是关于Laravel 关系查询加载 hasMany + BelongsToMany的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 急切加载与添加子句的关系?

带有嵌套关系的 Laravel 急切加载

Laravel 5.8 中 hasMany 关系的条件

使用 Eloquent Laravel 获取 hasMany 关系

Laravel 关系,hasmany 和 blongstomany

orderBy on hasMany 关系 laravel