无法在现有 table 上添加外键
Cannot add foreign key on already existing table
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');
});
}
我在另一个 table 中创建了完全相同的 FK,具有相同的关系,当时正在初始化 table。但是这个不起作用。我收到以下错误:
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)
查看其他帖子,关于这个问题,我只能找到列不是 unsigned
或关系中的列之一不存在的情况。在这里,我已经涵盖了这两种情况,但不知道问题可能是什么...
您在 table 中有一些数据意味着约束将失败,因为对于现有行,添加的列将设置为 NULL。
默认情况下,在迁移内部,每个列定义都不可为空。您必须指定 nullable 以允许外键为空值。
$table->integer('driver_user_id')->unsigned()->nullable()->after('main_trip_id');
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');
});
}
我在另一个 table 中创建了完全相同的 FK,具有相同的关系,当时正在初始化 table。但是这个不起作用。我收到以下错误:
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)
查看其他帖子,关于这个问题,我只能找到列不是 unsigned
或关系中的列之一不存在的情况。在这里,我已经涵盖了这两种情况,但不知道问题可能是什么...
您在 table 中有一些数据意味着约束将失败,因为对于现有行,添加的列将设置为 NULL。 默认情况下,在迁移内部,每个列定义都不可为空。您必须指定 nullable 以允许外键为空值。
$table->integer('driver_user_id')->unsigned()->nullable()->after('main_trip_id');