2016-03-26 45 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