簡體   English   中英

使用 Laravel 遷移創建外鍵時出現 MySQL 錯誤

[英]MySQL error when creating foreign key with Laravel migration

我設置了一個 Laravel 應用程序,並且正在使用Sentry 2進行用戶身份驗證。 我有一個名為Post的模型以及默認的哨兵User表。 我想讓一個用戶有很多帖子,一個帖子屬於一個用戶。 為了在我的數據庫模式中反映這一點,我需要在postsusers之間創建一個外鍵約束。

我寫的遷移如下:

public function up()
{
    Schema::table('posts', function(Blueprint $table)
    {
        $table->integer('user_id')->after('id')->nullable();
        $table->foreign('user_id')->references('id')->on('users');
    });
}

使用php artisan migrate運行它后,我在命令提示符中收到一個 MySQL 錯誤:

[照亮\\數據庫\\查詢異常]
SQLSTATE[HY000]: General error: 1005 Can't create table 'blog.dev.#sql-3bb_2d' (errno: 150) (SQL: alter table posts add constraint posts_user_id_foreign Foreign key ( user_id ) references users ( id ))

起初我認為發生此錯誤是因為users的主鍵列的定義與我的外鍵列user_id ,但是它們都定義為int(10)

從谷歌我了解到這個錯誤可能是由兩個列定義不同引起的,但這里似乎並非如此。

外鍵應該已經在數據庫中,因此我建議采取兩個步驟。 另外我建議使user_id列未簽名:

public function up()
{
    Schema::table('posts', function(Blueprint $table)
    {
        $table->integer('user_id')->after('id')->nullable()->unsigned();
    });

    Schema::table('posts', function(Blueprint $table)
    {
        $table->foreign('user_id')->references('id')->on('users');
    });
}
public function up()
{
    Schema::table('posts', function(Blueprint $table)
    {
        $table->integer('user_id')->nullable()->after('id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
    });
}

我解決了

Schema::disableForeignKeyConstraints();

在第一次遷移之前和

Schema::enableForeignKeyConstraints();

在上次遷移中

截屏

暫無
暫無

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

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