2016-11-29 68 views
0

我有一个递归关系(段和子段) 定义为这ReportSection模式:Laravel关系集合迭代返回布尔

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但错误仍然存​​在

回答

0

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

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

是啊,我现在认识到这一点,也许早就抓住了,但发生错误的事项之前,我没有进行更改, $ rSection仍然是1. – Ave

+0

这里是一样的:'$ report-> sections-> where('section_id',$ section-> id) - > get()' –

+0

我想你必须把它称为一种方法查询 – Ave

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) {