Laravel Eloquent 查询模型,在 n 到 m 关系中具有精确的多个关联

标签 laravel eloquent where-in

我有一个项目,其中有以下模型:

  • 产品
  • 特征类型
  • 功能
  • 变体

表和关系如下:

Database Schema Diagram

我有一个请求,希望从具有某些特定功能产品中检索变体。 一个 Variant 可以有 1 个或多个 Feature,但如果我给出一个 Feature,我希望拥有所有 Variants,并且如果我提供更多功能,则对Variants进行更具体的搜索,直到我只有一个Variant,它只能有一组特定的功能

这是我现在的代码:

$variants =  $product
->variants()
->whereHas('features', function($query) {
    $query->whereIn('id', json_decode(request('features')));
})
->with('features', 'features.featureType')
->get();  

request('features') 包含一个字符串化数组,其 ID 为 Features

我使用 Eloquent 的 whereIn 方法,认为它只会为我提供具有请求中给出的所有 Features 的变体。

但是在再次检查文档时,我发现它将返回请求中至少提供了一个 Feature 的任何 Variants,而这不是我在这里需要的。

如何使 Eloquent 的查询仅返回与请求给出的所有 Features 关联的 Variants

预先感谢您的帮助! ;)

最佳答案

whereHas() 接受第四个参数,其中包含行数:

$variants = $product
    ->variants()
    ->whereHas('features', function($query) use ($features) {
        $query->whereIn('id', $features);
    }, '=', count($features))
    ->with('features', 'features.featureType')
    ->get();

关于Laravel Eloquent 查询模型,在 n 到 m 关系中具有精确的多个关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56691313/

相关文章:

javascript - axios调用,使用vue将响应数据获取到选择选项中

php - Laravel 的 whereHas 表现不佳

Laravel Eloquent 表中两列之间的位置

postgresql - 如何检查值是否在列表中或列表是否为空?

MySQL select where in but not in with join

mysql - SQL 多重 Select ... where id in 和 DISTINCT

javascript - 如何在 laravel 5 提交成功后显示一个甜蜜的警告框?

laravel - 是否可以在Laravel Passport中禁用路线?

php - 如何在 Eloquent Laravel 中过滤计算字段(追加)?

php - 拉拉维尔 5.2 : defined user and get information from other database table