1215不能添加外键

ekqde3dh  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(282)

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` 通常情况下,当父表不存在并且我们在表中使用它的列作为外键时会发生这种情况,但是可以看到,应该首先创建users表,然后创建videos表,然后才是为什么会出现这种错误。
用户表

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');
});

9rygscc1

9rygscc11#

啊,你改变你的身份证在表视频试试这个

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');
    }
kyxcudwk

kyxcudwk2#

嗨,试试这对我来说很好

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

然后是工匠migrate:refresh

x6yk4ghg

x6yk4ghg3#

添加ondelete cascade并将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');
});

相关问题