簡體   English   中英

無法在 Laravel 遷移中添加外鍵約束

[英]Cannot add foreign key constraint in Laravel Migration

我發現發布了幾十個類似的問題,但在我的情況下似乎沒有一個解決方案有效。 當我運行“php artisan migrate:fresh”時,它拋出了錯誤......

Illuminate\Database\QueryException:SQLSTATE[HY000]:一般錯誤:1215 無法添加外鍵約束(SQL:alter table slicer_profiles添加約束slicer_profiles_user_id_foreign外鍵( user_id )在刪除級聯時引用usersid

  • 創建的所有表都是 InnoDB
  • 'users' 表是在我的表之前創建的
  • 我將代碼分為兩步,然后分配外鍵

    Schema::create('slicer_profiles', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned()->index(); $table->string('title'); $table->text('description'); $table->string('slicer'); $table->string('machine'); $table->softDeletes(); $table->timestamps(); }); Schema::table('slicer_profiles', function($table) { $table->foreign('user_id')->unsigned() ->references('id') ->on('users') ->onDelete('cascade'); });

我檢查了 auth users 表,它似乎使用了 UNSIGNED BIGINT,所以我也嘗試在引用上設置 ->unsigned(),但沒有改變。 任何解決此問題的幫助將不勝感激!

如果users.id字段是 BIGINT,那么您需要將 slicer_profiles 上的users_idslicer_profiles為 BIGINT,以便 2 個字段具有完全匹配的類型。

Schema::create('slicer_profiles', function (Blueprint $table) {
    ...
    $table->bigInteger('user_id')->unsigned()->index();
    // or $table->unsignedBigInteger('user_id')->index();
    ...
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM