Laravel Relationship Collection迭代返回boolean

时间:2016-11-29 13:09:02

标签: laravel eloquent laravel-5.2 relationship

我有一个递归关系(部分和子部分) 在ReportSection模型中定义为:

function sub_sections() {
  return $this->hasMany('App\ReportSection', 'parent_id');
}

我试图像这样迭代它:

$section = Section::find($id);
        \DB::beginTransaction();
        try {
          foreach(ReportForm::unlockedForm($section->form_id)->get() as $report) {
            foreach($report->sections()->where('section_id', $section->id)->get() as $reportSections) {
              \Log::info($reportSections);
              foreach($reportSections as $rSection) {
                \Log::info($rSection);
                foreach($rSection->sub_sections as $subSection) {

\Log::info($reportSections);按预期提供{"id":3,"report_form_id":1,"name_en":"DDD","name_fr":"DDD","created_at":"2016-11-29 07:47:24","updated_at":"2016-11-29 07:47:32","section_id":118,"parent_id":1,"order":99,"hidden":0}

但迭代通过它以某种方式给出一个布尔\Log::info($rSection);给出1

最后一行foreach($rSection->sub_sections as $subSection) {给出错误'Trying to get property of non-object'

为什么迭代通过关系集合会给出一个布尔值?我做错了什么?

编辑:将sub_sections()更改为sub_sections但错误仍然存​​在

2 个答案:

答案 0 :(得分:0)

您应该调用属性名称而不是方法:

foreach($rSection->sub_sections as $subSection)
{}

答案 1 :(得分:0)

好好休息一下后,我能够发现问题是我在同一个集合中迭代两次。

而不是

 foreach(ReportForm::unlockedForm($section->form_id)->get() as $report) {
            foreach($report->sections()->where('section_id', $section->id)->get() as $reportSections) {
              foreach($reportSections as $rSection) {

应该是

 foreach(ReportForm::unlockedForm($section->form_id)->get() as $report) {
            foreach($report->sections()->where('section_id', $section->id)->get() as $rSection) {
相关问题