为什么在Laravel 5.8中创建外键失败? [英] Why is creating Foreign Key in Laravel 5.8 failing?

查看:69
本文介绍了为什么在Laravel 5.8中创建外键失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的迁移脚本在旧版本的Laravel中运行平稳,但是我将其添加到了新的Laravel 5.8中并运行了该脚本.我正在Error: foreign key was not formed correctly

The migration script below was running smoothly in an older version of Laravel but I added it to my fresh Laravel 5.8 and ran the script. I'm getting Error: foreign key was not formed correctly

评估迁移:

public function up() { 
    Schema::create('evaluation', function (Blueprint $table) { 
        $table->increments('id'); 
        $table->integer('user_id')->unsigned()->index(); 
        $table->timestamps();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

用户迁移:

public function up() { 
    Schema::create('users', function (Blueprint $table) { 
        $table->bigIncrements('id'); 
        $table->timestamps();
    });
}

推荐答案

正如我们在上面的注释中所讨论的,外键列必须与它所引用的主键具有相同的数据类型.

As we discussed in the comments above, a foreign key column must be the same data type as the primary key it references.

您将user.id主键声明为$table->bigIncrements('id'),它在MySQL语法中变为BIGINT UNSIGNED AUTO_INCREMENT.

You declared your user.id primary key as $table->bigIncrements('id') which becomes BIGINT UNSIGNED AUTO_INCREMENT in MySQL syntax.

必须将外键声明为$table->unsignedBigInteger('user_id'),在MySQL中将变为BIGINT UNSIGNED,使其与user.id列的外键兼容.

You must declare the foreign key as $table->unsignedBigInteger('user_id') which will become BIGINT UNSIGNED in MySQL, making it compatible with being a foreign key to the user.id column.

这篇关于为什么在Laravel 5.8中创建外键失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆