2016-03-26 61 views
0

在索引控制器中,我不需要任何條件,因此數據可以非常清晰地檢索所有關係模型。laravel在belongsToMany relationshaip中添加條件

$questions = Question::with('user','courses','subjects')->take(10)->orderBy("id","DESC")->get(); 

這與所有相關數據返回的問題列表像usercoursessubject 但在課程控制器時嘗試檢索與同和附加條件的數據當然蛞蝓那麼它的返回錯誤。

$questions = Question::with('user','courses','subjects')->where("slug",$course)->take(10)->orderBy("id","DESC")->get(); 

由於其增加了有關表查詢這個條件,所以沒有slug coloumn。 當我與course類檢索它返回正確的結果,但subjectsusers缺少

$questions = Course::with("question")->where("nick_name",$course)->orWhere("slug",$course)->orderBy("id","DESC")->take(10)->get(); 

然後,我怎麼能得到所有相關數據。 和課程模式有

public function question(){ 
    return $this->belongsToMany('App\Models\Question','university_questions')->take(10); 
} 

和問題模型具有

public function courses(){ 
    return $this->belongsToMany('App\Models\Course','course_questions'); 
} 
public function subjects(){ 
    return $this->belongsToMany('App\Models\Subject','subject_questions'); 
} 
public function years(){ 
    return $this->hasMany('App\Models\QuestionYear'); 
} 

缺什麼在這裏,請幫助。

回答

2

,如果你想獲得多重關係,你需要傳遞數組,這樣

$questions = Course::with([ 
       'questions.user', 
       'questions.courses', 
       'questions.subjects' 
       ]) 
       ->take(10) 
       ->where("slug",$slug) 
       ->orderBy("id","DESC") 
       ->get(); 
+0

但蛞蝓是完全沒問題的表是在課程表中。 – Jitendra

+0

哦,對不起我的mystake,如果你想添加條件相關的模型,你需要使用回調函數,我現在編輯答案 – Hrach

+0

謝謝,但我也試過這個,它返回所有的問題,如果問題有過程,然後這在那裏添加條件。意味着我會得到所有的問題,這種情況只適用於當然,如果slu found發現它返回課程,否則爲空。 – Jitendra