繁体   English   中英

laravel在belongsToMany关系中添加条件

[英]laravel add conditions in belongsToMany relationshaip

在索引控制器中,我不需要任何条件,因此可以使用所有关系模型非常清晰地检索数据。

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

这将返回包含所有相关数据(如user coursessubject的问题列表,但是在课程控制器中,当尝试使用相同的数据并为课程设置添加条件时返回错误。

$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');
}

这里缺少什么,请帮忙。

如果要获得多个关系,则需要传递数组,像这样

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM