Laravel 6 多对多关系

Laravel 6 many to many relationship

在laravel 6中,我有2个模型

class Teacher {

}

class Students {

}

我有第三个模特要加入 tables

class TeacherStudent {

}

现在我怎样才能找到所有没有被特定学生订阅的老师?

例如:
Teacher1、Teacher2、Teacher3、Teacher4 在Teacher table
和 Student1, Student2, Student3, Student4 在 Student table

学生1订阅了老师1、老师2
学生2订阅了老师1、老师4
学生 3 订阅了教师 2

这里,以Student1登录,想看未订阅的老师,应该得到Teacher3和Teacher4
Student4 登录,当我想查看未订阅的教师时,我应该得到 all teachers 等等

我假设您已经定义了模型中的所有关系

// in your controller
$user = auth()->user();

// where 'students' is a many-to-many relationship you have in you Teacher model
$teachers = Teacher::whereDoesntHave('students', function($query) use($user) {
    return  $query
          ->where('user_id', $user->id);
});

以上查询将检索不属于当前已验证用户的所有教师。

如果您还没有在模型中定义任何关系。它们应该看起来像这样:

// Teacher model
public function students() {
  // many to many relationship
  return $this->belongsToMany('App\Student', 'subscriber'); // replace subscribers with your pivot table
}

一个学生模型:

// Student model
public function teachers() {
   // many to many relationship
   return $this->belongsToMany('App\Teacher', 'subscriber'); // replace subscribers with your pivot table
}

PS:还没有测试过这些,如果它们不起作用请告诉我