samedi 26 mars 2016

laravel add conditions in belongsToMany relationshaip

In index controller i don't need any condition so data retrieves very clearly with all relational models.

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

This return the question list with all related data like user courses and subject But in courses controller when try to retrieve data with same and adding condition for course slug then its return error.

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

Because its adds this condition in question table query so there are no slug coloumn. And When i retrieved with course class it return correct result but the subjects and users are missing

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

Then how can i get all related data. And the course model has

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

and question model have

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

What is missing here please help.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire