Php Can';t向透视表添加外键约束 背景:
我正在用Laravel开发一个应用程序,供教练记录他们运动队在一个赛季中的比赛。目前,我正在尝试创建一个透视表,以将Php Can';t向透视表添加外键约束 背景:,php,mysql,database,foreign-keys,laravel-migrations,Php,Mysql,Database,Foreign Keys,Laravel Migrations,我正在用Laravel开发一个应用程序,供教练记录他们运动队在一个赛季中的比赛。目前,我正在尝试创建一个透视表,以将团队映射到轮(匹配) 关系概述: 一个用户有一个团队,但是团队表(用户id)中的用户表的外键是可为空的,因为管理员将创建许多团队,但是团队的用户id将在以后分配 团队属于用户(教练) 在回合和团队之间存在多对多关系(这就是数据透视表的作用) 要将团队映射到轮,我有一个轮_团队表,表中有两个外键:轮_id和团队_id 尝试在round\u team表上创建外键(team\u id)时
团队
映射到轮
(匹配)
关系概述:
一个用户
有一个团队
,但是团队
表(用户id
)中的用户
表的外键是可为空的
,因为管理员将创建许多团队
,但是团队
的用户id
将在以后分配
团队
属于用户
(教练)
在回合
和团队
之间存在多对多关系(这就是数据透视表的作用)
要将团队
映射到轮
,我有一个轮_团队
表,表中有两个外键:轮_id
和团队_id
尝试在round\u team
表上创建外键(team\u id
)时,控制台中出现错误(运行php artisan migrate
后):
我假设这是由于团队
id
可以为空
。。。如果是这种情况,我如何才能成功地添加此约束?否则,是什么导致了错误
迁移:
很多时候,这种错误是因为数据库中的记录具有空白的外部值。所有的团队记录都有一个有效的团队id??数据库完全是空的。我认为这是在
$table->integer('team\u id')->unisigned()上的输入错误代码>,未签名是的,你确实是对的。非常感谢。
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `round_team` add constraint `round_team_team_id_foreign` foreign key (`team_id`) references `teams` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->enum('role', ['coach', 'admin'])->default('coach');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('teams', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable();
$table->string('name')->unique();
$table->string('slug')->unique();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
Schema::create('rounds', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('round_team', function (Blueprint $table) {
$table->increments('id');
$table->integer('round_id')->unsigned();
$table->integer('team_id')->unisigned();
$table->timestamp('date')->nullable();
$table->timestamps();
$table->foreign('round_id')->references('id')->on('rounds');
$table->foreign('team_id')->references('id')->on('teams');
});