我正在尝试访问 Blade View 中的嵌套数据,但我尝试的所有操作似乎都会导致一个或另一个错误。我猜测这与嵌套的相关数据是一个集合有关,但我认为如果我循环遍历这个数据,我就可以访问我需要的内容。代码如下。
模型选项组
class OptionGroup extends Model {
protected $table = 'option_groups';
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function option_choices()
{
return $this->hasMany('App\OptionChoice');
}
}
模型选项选择
class OptionChoice extends Model {
protected $table = 'option_choices';
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function option_group()
{
return $this->belongsTo('App\OptionGroup');
}
}
模型模块问题
class ModuleFftQuestion extends Model {
protected $table = 'module_questions';
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function option_group()
{
return $this->belongsTo('App\OptionGroup');
}
}
模块 Controller
....
$questions = ModuleQuestion::with('option_group.option_choices')
->where('enabled', '=', 1)
->get()
->sortBy('id', true);
return view('modules.index', compact('questions'));
查看模块/index.blade.php
....
@foreach($questions as $question)
<section>
<ul>
@foreach($question->option_group->option_choices as $choice)
<li>
echo something here maybe {!! $choice->name !!}
</li>
@endforeach
/ul>
</section>
@endforeach
我认为我可以在上面的 View 中执行此操作,但这会引发错误:
ErrorException in 35dc55260ec747349284c8d119dae7bf line 17:
Trying to get property of non-object (View: /www/resources/views/modules/index.blade.php)
如果我注释掉嵌套的 foreach,我可以在 laravel 调试栏中看到查询,如下所示:
select * from `module_questions` where `enabled` = '1'
select * from `option_groups` where `option_groups`.`id` in ('2', '0', '3', '4', '5', '1')
select * from `option_choices` where `option_choices`.`option_group_id` in ('1', '2', '3', '4', '5')
我想说我的关系很好,如下:
- An option_group has many option_choices
- An option_choice belongs to one option_group
- A module_question belongs to one option_group
我显然错过了一些东西,有些东西还没有完全吸引我,我是 Laravel 的新手,一直在学习,但这让我难住了。
这就是我试图访问 View 中的 option_choice 数据的方式,还是有更好的方法使用 eloquent 进行查询,以便更轻松地访问 View 中的 option_choice 数据。
我们将不胜感激任何帮助。
问候 中号
最佳答案
对于您的一个问题,option_group
中可能没有任何项目,因此您无法访问 option_choices
。您应该这样添加一项额外的检查:
@foreach($questions as $question)
<section>
<ul>
@if ($question->option_group)
@foreach($question->option_group->option_choices as $choice)
<li>
echo something here maybe {!! $choice->name !!}
</li>
@endforeach
@endif
</ul>
</section>
@endforeach
关于php - Laravel 5.0 : Querying and displaying child objects in view from nested relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28868155/