[英]Laravel 8 Migration “General error: 1215 Cannot add foreign key constraint”
[英]Laravel migration General error: 1215 Cannot add foreign key constraint Laravel 7.x
我想在我的 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:alter table images
添加約束images_user_id_foreign
外鍵( user_id
)在刪除級聯上引用users
( id
))
我已經在谷歌上搜索過但沒有成功,有人可以幫助我嗎?
謝謝
您沒有正確設置unsigned
。
代替:
$table->bigInteger('user_id')->unsigned;
經過:
$table->bigInteger('user_id')->unsigned();
由於user_id
未簽名,因此定義與users
表的id
不匹配,這意味着您無法設置外鍵。
你也可以這樣做:
$table->unsignedBigInteger('user_id');
從 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
您在unsiged()
中缺少括號
->unsigned()
將INTEGER
列設置為UNSIGNED
(MySQL)
改變
$table->bigInteger('user_id')->unsigned;
到
$table->bigInteger('user_id')->unsigned();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.