我有以下三种型号:
在我的Stream
模型中,我有:
public function FieldRoutes()
{
return $this->hasMany(FieldRoute::class);
}
然后,在我的FieldRoute模型中,我有:
public function fields()
{
return $this->hasMany(Field::class);
}
我正在尝试通过Field
访问FieldRoute
模型,就像这样:
$stream = Stream::find(1);
$routeFields = $stream->FieldRoutes()->fields;
但是,上面的错误给了我
未定义的属性:Illuminate \ Database \ Eloquent \ Relations \ HasMany :: $ fields
我是否仅通过拥有fields
对象就能获得属于FieldRoute
的{{1}}吗?
答案 0 :(得分:1)
您将需要一些嵌套循环来处理嵌套关系。但是首先,您遇到的错误是由于缺少闭包;您需要在关系名称后拨打->get()
:
$routeFields = $stream->FieldRoutes()->get();
// Or, omit the ()
$routeFields = $stream->FieldRoutes;
接下来,进行一些循环以获取字段:
foreach($routeFields AS $routeField){
$fields = $routeField->fields()->get();
// Or, again, omit the () (in fact, never use () in a loop)
$fields = $routeField->fields;
}
最后,又有一个循环访问每个Field
的属性:
foreach($fields AS $field){
// Do whatever you want with $field...
}
总的来说,这看起来像:
$stream = Stream::with(["FieldRoutes", "FieldRoutes.fields"])->find(1);
$routeFields = $stream->FieldRoutes;
foreach($routeFields AS $routeField){
$fields = $routeField->fields;
foreach($fields AS $field){
// Do whatever with $field
}
}
// Simplified
foreach($stream->FieldRoutes AS $routeField){
foreach($routeField->fields AS $field){
// Do whatever with $field
}
}
另外,请修正您的函数名称FieldRoutes
,应为fieldRoutes
(函数名称为camelCase
)
注意:我已经使用::with()
来“提前加载”关系,因此您在循环时不必查询它们,因为这会极大地影响性能。
答案 1 :(得分:0)
尝试
$stream = Stream::with('FieldRoute.Field')->get();
答案 2 :(得分:0)
您可以尝试快速加载并提取值。
{{1}}