Laravel | Pivot table、table 名称冲突
Laravel | Pivot table, table names clashing
我正在尝试创建一个枢轴 table 以便 link 教师对某个学科进行指导,然后 link 教师对某个学科进行指导。
我有这样的老师 table 架构。
| id | first_name | last_name | created_at | updated_at
和这样的枢轴 table 架构。
| id | teacher_id | subject_id
主题 table 架构是这样的。
| id | name | created_at | updated_at
这是一个非常基本的 table 结构,同时我尝试找出来龙去脉。
我的 Teacher.php
模型中有这段代码,它扩展了 Eloquents 模型。
老师可以分配多个科目。
return $this->belongsToMany('App\Models\TeacherSubject', 'teacher_subjects', 'teacher_id', 'id');
这是我遇到的错误..
Syntax error or access violation: 1066 Not unique table/alias: 'teacher_subjects' (SQL: select teacher_subjects.*, teacher_subjects.teacher_id as pivot_teacher_id, teacher_subjects.id as pivot_id from teacher_subjects inner join teacher_subjects on teacher_subjects.id = teacher_subjects.id where teacher_subjects.teacher_id in (1))
对我来说,似乎 belongsToMany
正在将两个 table 重命名为同一个名字,这让我完全困惑。
谁能指出我哪里出错了?
您的枢轴 table 不需要模型,laravel 会为您处理关系。只需使用:
教师模型
$this->belongsToMany(Subject::class, 'teacher_subjects');
科目模型
$this->belongsToMany(Teacher::class, 'teacher_subjects');
我正在尝试创建一个枢轴 table 以便 link 教师对某个学科进行指导,然后 link 教师对某个学科进行指导。
我有这样的老师 table 架构。
| id | first_name | last_name | created_at | updated_at
和这样的枢轴 table 架构。
| id | teacher_id | subject_id
主题 table 架构是这样的。
| id | name | created_at | updated_at
这是一个非常基本的 table 结构,同时我尝试找出来龙去脉。
我的 Teacher.php
模型中有这段代码,它扩展了 Eloquents 模型。
老师可以分配多个科目。
return $this->belongsToMany('App\Models\TeacherSubject', 'teacher_subjects', 'teacher_id', 'id');
这是我遇到的错误..
Syntax error or access violation: 1066 Not unique table/alias: 'teacher_subjects' (SQL: select teacher_subjects.*, teacher_subjects.teacher_id as pivot_teacher_id, teacher_subjects.id as pivot_id from teacher_subjects inner join teacher_subjects on teacher_subjects.id = teacher_subjects.id where teacher_subjects.teacher_id in (1))
对我来说,似乎 belongsToMany
正在将两个 table 重命名为同一个名字,这让我完全困惑。
谁能指出我哪里出错了?
您的枢轴 table 不需要模型,laravel 会为您处理关系。只需使用:
教师模型
$this->belongsToMany(Subject::class, 'teacher_subjects');
科目模型
$this->belongsToMany(Teacher::class, 'teacher_subjects');