如何通过数据透视表列按多对多关系对表进行排序?

时间:2019-09-11 18:36:35

标签: laravel eloquent

我想按教师所属学校对教师表进行排序。学校的名称是数据透视表中的一列。

我有一个老师桌,一个学校桌和一个数据透视表。教师的表格具有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");
 }
 }
  1. 我的学校模式:
    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");
    }
    }
  1. 我当前的老师的控制者(按“ ID”而不是学校名称对老师进行排序):
    public function listBySchool(Request $req) {
    $teachers = Teacher::orderBy('ID')->paginate(200);
    return view("listTeachersBySchool", compact("teachers"));
    }
  1. 我的观点:
    @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

请帮助我使视图显示按学校名称排序的教师。 ¡吨!

1 个答案:

答案 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();