php - 拉维尔 |数据透视表,表名冲突

标签 php mysql laravel eloquent lumen

我正在尝试创建一个数据透视表,以便将教师链接到一个主题,然后将教师链接到一个主题。

我有这样的教师表架构。

| id | first_name | last_name | created_at | updated_at

数据透视表架构是这样的。

| id | teacher_id | subject_id

主题表架构是这样的。

| id | name | created_at | updated_at

这是一个非常基本的表结构,同时我尝试找出来龙去脉。

我的 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 都将两个表重命名为相同的名称,这让我完全感到困惑。

谁能指出我哪里做错了?

最佳答案

您的数据透视表不需要模型,laravel 会为您处理关系。只需使用:

教师模型

 $this->belongsToMany(Subject::class, 'teacher_subjects');

主题模型

 $this->belongsToMany(Teacher::class, 'teacher_subjects');

关于php - 拉维尔 |数据透视表,表名冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48834469/

相关文章:

mysql - SELECT 并每小时获取结果

php - 如何使用 php 将 API 数据(数组)存储到数据库中

mysql - MySQL 计算行之间的差异

laravel - axios 和 this.$axios 的区别

php - Auth::check() 返回 false Laravel 5.4

PHP 邮件总是给我 undefined index ,有帮助吗?

php - 使用 PHP/MySQL 连接到 phpMyAdmin 数据库

php - PHP 中的 MongoDB 游标,它是在查询执行时将所有记录带到客户端还是在游标迭代时将所有记录一条一条地带到客户端?

php - 共享主机上的 Symfony 2 - 允许的内存大小已耗尽

php - Laravel 5.1 本地化