mysql - 无法在现有表上添加外键

标签 mysql laravel laravel-4 foreign-keys database-migration

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/

相关文章:

mysql - 如何使用数组指针从 Perl 中的 MySQL 查询中获取多条记录?

mysql - 获取排序行的位置

php - Laravel:模型内验证。多重验证规则

php - Laravel 空白白屏

mysql - 将具有两个 FK 列的 ORM 推向同一个外部表

mysql - 查找数据库中的哪些圆形区域包含 map 上的特定点

php - Laravel Eloquent 递归 child

php - 拉维尔 5 : How to use simple birth date middleware(before filter)?

php - 使用 laravel Controller 从 $.ajax 调用接收数据

php - 从 MyISAM 切换到 InnoDB 后 Eloquent save() 不工作