簡體   English   中英

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

[英]Migration: Cannot add foreign key constraint in Laravel 6

我正在嘗試在 Laravel 中創建外鍵。 但是,當我使用 Artisan 遷移我的表時,我收到以下錯誤。

Illuminate\Database\QueryException:SQLSTATE[HY000]:一般錯誤:1215 無法添加外鍵約束(SQL:alter table posts添加約束posts_category_id_foreign外鍵( category_id )引用categoriesid ))

帖子遷移

Schema::create('posts', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->string('title');
    $table->string('slug')->unique();
    $table->longText('content');
    $table->string('image')->nullable();
    $table->uuid('author_id');
    $table->uuid('category_id');
    $table->timestamps();
    $table->foreign('author_id')->references('id')->on('users')->onDelete('set null');
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('set null');
});

類別遷移

Schema::create('categories', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->string('name');
    $table->string('slug')->unique();
    $table->uuid('parent')->nullable();
});

在您的posts架構中,您在刪除時將author_idcategory_id設置為 null,但您沒有將這些字段設置為可為空。 將定義更改為:

$table->uuid('author_id')->nullable();
$table->uuid('category_id')->nullable();

應該這樣做。

將您的外鍵聲明拆分為它們自己的 Schema 方法...

我不明白問題的原因,但這樣做一直對我有用。

Schema::create('posts', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->string('title');
    $table->string('slug')->unique();
    $table->longText('content');
    $table->string('image')->nullable();
    $table->uuid('author_id');
    $table->uuid('category_id');
    $table->timestamps();
});

Schema::table('posts', function(Blueprint $table) {
    $table->foreign('author_id')->references('id')->on('users')->onDelete('set null');
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('set null');
});

暫無
暫無

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

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