我在 Laravel 8 中有一個資料庫遷移,如下所示:
class CreateArticlesTable extends Migration
{
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('title');
$table->string('slug');
$table->text('description');
$table->text('body');
$table->string('imageUrl');
$table->string('tags');
$table->integer('viewCount')->default(0);
$table->integer('commentCount')->default(0);
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('articles');
}
}
但是每當我想運行它時,我都會收到此錯誤:
一般錯誤:1005 無法創建表elearning。articles(errno: 150 "外鍵約束的格式不正確")
我不知道這里出了什么問題,所以如果你知道如何解決這個問題,請告訴我......
uj5u.com熱心網友回復:
而不是使用
$table->integer('user_id')->unsigned();
利用
$table->unsignedBigInteger();
laravel 使用 unsignedBigInteger 是 20 位,而 unsignedInteger 只需要 11 位
https://laravel.com/docs/8.x/migrations#foreign-key-constraints
uj5u.com熱心網友回復:
用戶表和文章表的引擎是否相同并且都是InnoDB?MyISAM 不支持外鍵。如果是,文章表是否會在用戶表之后創建?如果答案是肯定的,那么:兩個欄位是否完全相同?我認為您的用戶 ID 是自動遞增的,如果是,則在外鍵中添加 unsigned :
$table->foreign('user_id')->unsigned()->references('id')->on('users')->onDelete('cascade');
uj5u.com熱心網友回復:
在 Laravel 8 上試試這個
$table->id();
$table->unsignedBigInteger('user_id')->unsigned();
$table->foreign('user_id')->on('users')->references('id')->onDelete('cascade');
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/393633.html
