traer algunos campos me resulta un poco consufo es posible que alguien me explique como hacerlo desde el modelo
I have the following tables tables
The table course_teacher is the pivot table and contains the field called "is_available".
I would like to make a query
that returns
course_name, teacher_name
and only show me the courses that are active.
Any suggestions on how to do that?
CodePudding user response:
I consider you're using m-n relationship, so your models will be like
class Course {
...
public function teachers(){
return $this->belongsToMany(Teacher::class, 'course_teacher');
}
public function avaiableTeachers(){
return $this->belongsToMany(Teacher::class, 'course_teacher')->wherePivot('available', 1);
}
}
class Teacher{
...
public class courses(){
return $this->belongsToMany(Course::class, 'course_teacher');
}
}
At this step, we have defined the m-n relationship for eloquent.
Then, if you want to get courses with assigned teachers (Only available), then the query will be like this:
$ courses = Course::with('avaiableTeachers')->paginate(10);