【问题标题】:Laravel 6 many to many relationshipLaravel 6 多对多关系
【发布时间】:2020-06-13 05:31:14
【问题描述】:

在 laravel 6 中,我有 2 个模型

class Teacher {

}

class Students {

}

我有第三个模型来加入表格

class TeacherStudent {

}

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

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

学生 1 订阅了教师 1、教师 2
Student2 订阅了 Teacher1、Teacher4
Student3 订阅了 Teacher2

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

【问题讨论】:

    标签: mysql sql laravel eloquent laravel-6


    【解决方案1】:

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

    // 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:还没有测试过,如果它们不起作用,请告诉我

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-15
      • 2018-01-22
      • 2016-02-26
      • 2016-01-04
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多