我想按教师所属学校对教师表进行排序。学校的名称是数据透视表中的一列。
我有一个老师桌,一个学校桌和一个数据透视表。教师的表格具有ID,姓氏,名字。学校表的ID为school_name。数据透视表('teacher_school')具有ID,school_ID,teacher_ID。我知道如何按老师的姓氏对老师的桌子进行排序,但不知道如何按学校名称对老师的表进行排序。
1。我的老师模型:
class Teacher extends Model
{
public $table = "teachers";
public $primaryKey = "ID";
public $timestamps = false;
public $guarded = [];
public function schools() {
return $this->belongsToMany("App\School", "teacher_school",
"teacher_ID", "school_ID");
}
}
class School extends Model
{
public $table = "schools";
public $primaryKey = "ID";
public $timestamps = false;
public $guarded = [];
public function teachers() {
return $this->belongsToMany("App\Teacher", "teacher_school", "school_ID", "teacher_ID");
}
}
public function listBySchool(Request $req) {
$teachers = Teacher::orderBy('ID')->paginate(200);
return view("listTeachersBySchool", compact("teachers"));
}
@foreach ($teachers as $teacher)
<tr>
<td>{{$teacher["ID"]}}</td>
<td>{{$teacher["lastname"]}}</td>
<td>{{$teacher["firstname"]}}</td>
<td>
@foreach ($teacher->schools as $school)
{{$school["school_name"]}}
@endforeach
</td>
</tr>
@endforeach
请帮助我使视图显示按学校名称排序的教师。 ¡吨!
答案 0 :(得分:0)
我假设您想按学校表中的学校名称对教师进行排序。因为上述数据透视表没有学校名称。
我建议使用多联接查询来实现所需的目标。
Teacher::select('teachers.*')
->join('teacher_school', 'teachers.id', '=', 'teacher_school.teacher_id')
->join('schools', 'teacher_school.school_id', '=', 'schools.id')
->orderBy('schools.school_name')
->distinct();