2016-07-31 105 views
0

我想在laravel的三個表之間建立關係。目前,我有三個型號在Laravel數據透視表中無法獲得關係

課堂

public function subjects(){ 
return $this->belongstoMany('Subject','subject_section_classroom'); 
} 


主題

我的表是

classrooms(id, name) 
sections(id, name) 
subjects(id, name) 
subject_section_classroom(id, classroom_id, section_id, subject_id) 

在我CLAS sroomController我有

public function assignsubjects($class_id, $section_id){ 
     $classroom = Classroom::find($class_id); 
     $section = Section::find($section_id); 
     $subjects = Subject::lists('name','id'); 
     $selected_subjects = $classroom->subjects()->where('section_id', '=', 1); 
     $subjects = Subject::lists('name','id'); 
     return view('assignedit', compact('classroom','section','subjects', 'selected_subjects')); 
} 

但我無法從上述關係中獲得selected_subjects。當我試圖讓上述查詢的SQL(帶 - > toSQL()),我得到

`"select * from `myschool_subjects` inner join `myschool_subject_section_classroom` on `myschool_subjects`.`id` = `myschool_subject_section_classroom`.`subject_id` where `myschool_subject_section_classroom`.`classroom_id` = ? and `section_id` = ?"` 

我想不通我在做什麼錯在這裏。 請幫助。

+0

我知道Laravel 4不支持三重錶轉動,因此如這個由@jarektkaczyk創建的包(https://github.com/jarektkaczyk/Eloquent-triple-pivot)已經創建。不知道是否有類似的Laravel 5存在。 –

+0

我認爲,你的表結構有點不對。你能否給我一些表格中的章節和主題的例子,以便我更好地理解你的邏輯。 – Phargelm

+0

實際上我想輸出課堂的所有科目。簡單的我想要透視表中的課堂科目,其中部分是定義的;) –

回答

0

我覺得你的問題是從 php $selected_subjects = $classroom->subjects()->where('section_id', '=', 1);

改過來了它: php $selected_subjects = $classroom->subjects()->where('section_id', '=', 1)->get();

相關問題