【问题标题】:Laravel migration General error: 1215 Cannot add foreign key constraint Laravel 7.xLaravel 迁移一般错误:1215 无法添加外键约束 Laravel 7.x
【发布时间】:2020-07-08 05:17:05
【问题描述】:

我想在我的 laravel 7.x 应用程序上使用两个模型:用户和图像:

# Users migration : 2014_10_12_000000_create_users_table.php

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

# Images migration : 2020_03_27_121254_create_models_images_table
Schema::create('images', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('user_id')->unsigned;
        $table->string('name');
        $table->timestamps();
    });

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

尝试迁移时,我收到以下错误:一般错误:1215 无法添加外键约束(SQL:更改表 images 添加约束 images_user_id_foreign 外键 (user_id) 引用 users (id)删除级联)

我已经在谷歌上搜索过,但没有成功,有人可以帮助我吗?

谢谢

【问题讨论】:

标签: laravel laravel-7


【解决方案1】:

unsiged() 中缺少括号

根据Laravel Documentation

->unsigned()INTEGER 列设置为UNSIGNED (MySQL)

改变

 $table->bigInteger('user_id')->unsigned;

$table->bigInteger('user_id')->unsigned();

【讨论】:

    【解决方案2】:

    问题

    您没有正确设置unsigned

    解决方案

    替换:

    $table->bigInteger('user_id')->unsigned;
    

    作者:

    $table->bigInteger('user_id')->unsigned();
    

    说明

    由于user_id 不是无符号的,因此定义与users 表的id 不匹配,这意味着您无法设置外键。

    在 Laravel 7.x 之前

    你也可以这样做:

    $table->unsignedBigInteger('user_id');
    

    Laravel 7.x

    从 Laravel 7 开始,您可以在 users 迁移中这样做:

    Schema::table('users', function (Blueprint $table) {
        $table->id();
        // ...
    });
    

    在您的images 迁移中:

    Schema::table('users', function (Blueprint $table) {
        // ...
        $table->foreignId('user_id')->constrained();
    });
    

    您可以在这里找到更多信息:https://laravel.com/docs/7.x/migrations#foreign-key-constraints

    【讨论】:

      猜你喜欢
      • 2021-03-29
      • 2021-06-18
      • 2019-07-27
      • 2020-06-12
      • 2019-12-27
      • 2019-03-02
      • 2019-09-08
      • 2018-07-29
      • 2018-07-29
      相关资源
      最近更新 更多