2016-11-29 65 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) {