public function up()
{
Schema::table('partial_trips', function(Blueprint $table)
{
$table->unsignedInteger('driver_user_id')->after('main_trip_id');
});
Schema::table('partial_trips', function(Blueprint $table)
{
$table->foreign('driver_user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
当表初始化时,我在另一个表中创建了完全相同的具有相同关系的 FK。但这不起作用。我收到以下错误:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or u
pdate a child row: a foreign key constraint fails (`bpr`.`#sql-7c82_5
7d`, CONSTRAINT `partial_trips_driver_user_id_foreign` FOREIGN KEY (`
driver_user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE)
查看其他帖子,关于该问题,我只能找到列不是无符号
或关系中的列之一不存在的情况。在这里,我已经介绍了这两种情况,但不知道问题可能是什么......
最佳答案
表中有一些数据意味着约束将失败,因为添加的列将针对现有行设置为 NULL。 默认情况下,在迁移内部每个列定义都不可为空。您必须指定 nullable 以允许外键为空值。
$table->integer('driver_user_id')->unsigned()->nullable()->after('main_trip_id');
关于mysql - 无法在现有表上添加外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29479236/