【问题标题】:Laravel migration fails with SQLSTATE[HY000]: General error: 1215Laravel 迁移失败并出现 SQLSTATE[HY000]:一般错误:1215
【发布时间】:2020-05-13 20:01:51
【问题描述】:

我正在尝试使用 laravel 添加迁移。这是 mi 迁移文件。

public function up() {
    Schema::create('sl_categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title')->nullable();
        $table->integer('user_id')->unsigned()->nullable();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->softDeletes();
        $table->timestamps();
    });

    Schema::create('sl_images', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('image')->nullable();
        $table->integer('sl_category_id')->unsigned()->nullable();
        $table->integer('display_order')->nullable();
        $table->softDeletes();
        $table->timestamps();
    });

    Schema::table('sl_images', function(Blueprint $table) {
        $table->foreign('sl_category_id')->references('id')->on('sl_categories')->onDelete('cascade');
    });
}

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

但不幸的是,我遇到了这个错误。

Illuminate\Database\QueryException : SQLSTATE[HY000]: 一般错误: 1215 无法添加外键约束(SQL:alter table sl_images 添加约束sl_images_sl_category_id_foreign外键 (sl_category_id) 在删除时引用 sl_categories (id) 级联)

【问题讨论】:

    标签: laravel-5 laravel-migrations


    【解决方案1】:

    我终于找到了答案。问题是 InnoDB 不允许在列引用不匹配列类型的情况下创建外键约束。如果简单地说,

    这是一个大整数

    $table->bigIncrements('id'); 
    

    这是一个简单的整数。,

     $table->integer('sl_category_id')->unsigned()->nullable();
    

    所以我们要把后面的那行改成bigInteger

    $table->bigInteger('sl_category_id')->unsigned()->nullable();
    

    我添加这个答案以防其他人发现它的一些用途。

    【讨论】:

      猜你喜欢
      • 2019-07-27
      • 2020-03-19
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 1970-01-01
      • 2018-07-29
      相关资源
      最近更新 更多