[英]Laravel 9.X.X error when trying to add foreign key with 'php artisan migrate'
[英]Laravel incompatible foreign key error when running php artisan migrate
我試圖在 laravel 遷移中創建一個外鍵,它引用同一個表上的一列。 它是這樣的
$table->bigInteger('category_id');
$table->unsignedBigInteger('parent_id')->nullable();
$table->foreign('parent_id')->references('category_id')->on('categories')->onDelete('set null')->onUpdate('cascade');
當我運行php artisan migrate:fresh
它返回以下錯誤
SQLSTATE[HY000]: General error: 3780 Referencing column 'parent_id' and referenced column 'category_id' in foreign key constraint 'categories_parent_id_foreign' are incompatible.
從我在遷移中寫的內容來看似乎是正確的,但不確定是什么導致了這種情況。
bigIngeger
和unsignedBigInteger
不兼容。
您必須使用相同的類型。
只需用bigInteger
替換unsingedBigInteger
;
$table->unsignedBigInteger('category_id');
...並為您的category_id
字段添加索引。
$table->index('category_id');
我希望下面的代碼會起作用。
$table->bigIncrements('category_id');
$table->bigInteger('parent_id')->unsigned()->nullable();
$table->foreign('parent_id')->references('category_id')->on('categories')->onDelete('set null')->onUpdate('cascade');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.