在索引控制器中,我不需要任何条件,因此所有关系模型的数据检索都非常清晰。
$questions = Question::with('user','courses','subjects')->take(10)->orderBy("id","DESC")->get();
这将返回包含所有相关数据的问题列表,如user
、courses
和subject
但在航向控制器中,当试图以相同的条件检索数据并为航向段塞添加条件时,其返回错误。
$questions = Question::with('user','courses','subjects')->where("slug",$course)->take(10)->orderBy("id","DESC")->get();
因为它在问题表查询中添加了这个条件,所以没有slug
列。当我用course
类检索时,它返回正确的结果,但subjects
和users
缺少
$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');
}
这里缺少什么请帮忙。
如果你想获得多个关系,你需要传递数组,比如这个
$questions = Course::with([
'questions.user',
'questions.courses',
'questions.subjects'
])
->take(10)
->where("slug",$slug)
->orderBy("id","DESC")
->get();