【问题标题】:How the model relations are working in this context?在这种情况下,模型关系如何运作?
【发布时间】:2018-12-12 04:32:50
【问题描述】:

我需要创建一个数组,用于存储有关会议中特定注册的信息。是否需要存储:

  • 会议名称
  • 注册类型名称和价格
  • 还需要在数组中存储特定注册的每个注册类型的数量。数量可以使用参与者表获取,因为参与者表的结构如下:参与者表:id,registration_id,registration_type_id。因此可以计算一个特定的registration_id,该注册存在多少registration_type_id。

所以有必要做一个涉及3个表注册、会议和参与者的查询,所以查询应该像下面这样,因为模型关系,顺序是“conference.registrationTypes.participants”对吧?

    $registrationTypeDetails = Registration::with('conference.registrationTypes
    .participants')->find($registrationID);

那么下面这个foreach在$type_counts中存储了每种注册类型的数量,它的工作原理$type_counts显示:

 array:2 [▼
      "general" => 2
      "plus" => 1
    ]

代码:

  $type_counts = [];
    foreach ($registrationTypeDetails->participants as $p) {
        $name = $p->registration_type->name;
        if (!isset($type_counts[$name])) {
            $type_counts[$name] = 0;
        }
        $type_counts[$name]++;
    }

但我不明白 $type_counts 是如何显示的,关系如何工作以获得该结果,因为dd($registrationTypeDetails) 如下所示。

$registrationTypeDetails->participants 如下所示,关系为空,所以我不明白“$p->registration_type->name”如何显示注册类型名称。

Collection {#335 ▼
  #items: array:2 [▼
    0 => Participant {#350 ▼
      #relations: []
    }
    1 => Participant {#343 ▼
      #relations: []
    }
  ]
}

你了解 foreach 中的“$name = $p->registration_type->name;”如何获得正确的注册类型名称吗?

还有$registrationTypeDetails 显示:

Registration {#334 ▼
  #relations: array:1 [▼
    "conference" => Conference {#342 ▼
      #relations: array:1 [▼
        "registrationTypes" => Collection {#346 ▼
          #items: array:2 [▼
            0 => RegistrationType {#349 ▼
              #relations: array:1 [▼
                "participants" => Collection {#514 ▶}
              ]
            }
            1 => RegistrationType {#351 ▼
              #relations: array:1 [▼
                "participants" => Collection {#348 ▶}
              ]
            }
          ]
        }
      ]
    }
  ]
}

【问题讨论】:

  • 安装barryvdh/laravel-debugbar 并检查执行了哪些查询。这是一个很好的开始。

标签: laravel


【解决方案1】:

我观察到调用$registrationTypeDetails->participants 检索到Registration 的参与者关系(这不是eagerloaded)

当你打电话时:

Registration::with('conference.registrationTypes.participants')->find($registrationID);

它使用带有预加载关系的registrationId 检索Registration 的单个记录。但是,当您使用以下 $registrationTypeDetails->participants 时,您正在使用记录进行新查询,因此为什么您有 participants 模型集合,您可以在其上运行循环。

因为您已经定义了Registration 和Participant 之间的关系,所以它起作用了(这是错误的可能性有限)。

因为您在执行$registrationTypeDetails->participants 时没有急切加载participants 关系,所以您不希望它向您显示关系。尽管您注意到 dd($registrationTypeDetails) 向您显示了您的第一个预先加载的查询的结果。

在循环调用 $p->registration_type->name; 时会看到相同的效果。这也使用循环点的单个记录运行新查询(该记录具有引用 registration_type 关系的说 registration_type_id 的两个属性在participants 桌子上……等等……

总之,这就是为什么您可以在不使用with() 或load() 方法的情况下将相关模型作为集合访问的原因。

【讨论】:

    猜你喜欢
    • 2015-09-25
    • 2012-10-31
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 2020-06-18
    • 1970-01-01
    相关资源
    最近更新 更多