mysql - Laravel 抛出一般错误 : 1215 Cannot add foreign key constraint"when I create foreign keys

标签 mysql laravel foreign-keys

我正在使用 Laravel 6。我创建了一些迁移,但我无法让它们成功运行。这些是我的迁移。

    public function up()
{
    Schema::create('nationalities', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
        $table->engine = "InnoDB";
    });


    public function up()
{
    Schema::create('genders', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
        $table->engine = "InnoDB";
    });


    public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('firstname');
        $table->string('lastname');
        $table->string('street');
        $table->string('zip');
        $table->string('city');
        $table->date('birthdate');
        $table->string('gender');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
        $table->unsignedBigInteger('gender_id');
        $table->unsignedBigInteger('nationality_id');
        $table->engine = "InnoDB";
        $table->foreign('gender_id')->references('id')->on('gender');
        $table->foreign('nationality_id')->references('id')->on('nationality');
    });
}

执行php artisan migrate后,我收到此错误消息:

General error: 1215 Cannot add foreign key constraint (SQL: alter table users add constraint users_gender_id_foreign foreign key (gender_id) references gender (id))

我做错了什么?

最佳答案

您的表格名称是genders而不是gender,并且nationalities不是nationality:

更改:

...->references('id')->on('gender');
...->references('id')->on('nationality');

致:

...->references('id')->on('genders');
...->references('id')->on('nationalities');

关于mysql - Laravel 抛出一般错误 : 1215 Cannot add foreign key constraint"when I create foreign keys,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58845993/

相关文章:

mysql - 如何根据列的条件连接两个表?

mysql - 如何获取我在消息系统中与之交互的用户列表

mysql - 使用 ORDER BY 和 LIMIT 更新在 MYSQL 中不起作用

php - 当我在 laravel 和 mongodb 中单击分页时,过滤器不起作用

grails - 解析相关域对象的外键失败(obj.relatedId)

Sql字符串中的javascript默认值

Laravel nginx 默认文件

javascript - 使用 HTML/JavaScript+JQuery 的 HTTP GET 请求

python - 在 Django 管理界面的字段中包含来自另一个模型的多对多

mysql - 两个实体之间的多重关系,这是好的做法吗?