1215无法添加外键

时间:2018-12-03 07:17:10

标签: php mysql laravel laravel-migrations

Larvel 5.6.3 PHP 7.2.10

我收到php artisan migrate:fresh的以下错误

General error: 1215 Cannot add foreign key constraint (SQL: alter table `videos` add constraint `videos_video_identified_by_foreign` foreign key (`video_identified_by`) references `users` (`id`))

用户表迁移文件-> 2014_10_12_000000_create_users_table 视频表迁移文件-> 2018_12_02_122553_create_videos_table

通常会在父表不存在并且我们将其列用作表中的外键时发生,但是可以看出应该先创建用户表,然后再创建视频表,然后才知道为什么这个错误。

用户表

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

视频

 Schema::create('videos', function (Blueprint $table) {
    $table->increments('video_id');
    $table->text('video_link');
    $table->text('video_description');
    $table->string('video_category');
    $table->string('video_language');
    $table->unsignedInteger('video_identified_by');
    $table->timestamps();            
});

Schema::table('videos', function($table) {
    $table->foreign('video_identified_by')->references('id')->on('users');
});

3 个答案:

答案 0 :(得分:0)

嗨,这对我来说很好

<?php
    $table->integer('video_identified_by')->unsigned();
    $table->foreign('video_identified_by')->references('id')->on('user')
          ->onUpdate('RESTRICT')->onDelete('CASCADE');      
?>

然后php artisan migration:refresh

答案 1 :(得分:0)

啊,您可以在台式视频中更改自己的ID,请尝试

     Schema::create('videos', function (Blueprint $table) {
        $table->increments('id');
        $table->text('video_link');
        $table->text('video_description');
        $table->string('video_category');
        $table->string('video_language');
        $table->integer('video_identified_by')->unsigned();
        $table->foreign('video_identified_by')->references('id')->on('users')
          ->onUpdate('RESTRICT')->onDelete('CASCADE');   
        $table->timestamps();            
    });

    }
 public function down()
    {
        Schema::dropIfExists('videos');
    }

答案 2 :(得分:0)

添加onDelete级联并将unsignedInteger更改为unsigned

Schema::create('videos', function (Blueprint $table) {
$table->increments('video_id');
$table->text('video_link');
$table->text('video_description');
$table->string('video_category');
$table->string('video_language');
$table->unsigned('video_identified_by');
$table->timestamps();            
});

Schema::table('videos', function($table) {
$table->foreign('video_identified_by')->references('id')->on('users')- 
>onDelete('cascade');
});