簡體   English   中英

在Laravel遷移中添加外鍵約束

[英]Add foreign key constraints in Laravel migration

我知道很多人都問過同樣的問題很多次,但似乎我無法使相同的解決方案對我有用。

我無法為以下給出了up()的相關表設置外鍵:

//Migrate 1 Starts
public function up()
{
    Schema::create("UserTable", function($table){
        $table->tinyInteger("ApplicationID");
        $table->bigInteger("UserID");
        $table->string("UserName")->unique();
        $table->timestamps();
    });
}
//Migrate 1 Ends

//Migrate 2 Starts
public function up()
{
    Schema::create("Membership", function($table){
        $table->tinyInteger("ApplicationID");
        $table->bigInteger("UserID");
        $table->string("Password");
    }
}
//Migrate 2 Ends

//Migrate 3 Starts: This has the latest timestamp, so it runs after all tables are created
public function up()
{
    Schema::table('UserTable', function($table) {
        $table->primary("UserID");
        $table->foreign("UserID")->references("UserID")->on("Membership");
    });

    Schema::table('Membership', function($table) {
        $table->primary("UserID");
        $table->foreign("UserID")->references("UserID")->on("UserTable");
    });
}
//Migrate 3 Ends

我得到的錯誤是SQLSTATE[HY000]: General rror: 1215 Cannot add foreign key constraint (SQL: alter table 'Membership' add constraint membership_userid_foreign foreign key ('UserID') references 'UserTable' ('UserID'))錯誤SQLSTATE[HY000]: General rror: 1215 Cannot add foreign key constraint (SQL: alter table 'Membership' add constraint membership_userid_foreign foreign key ('UserID') references 'UserTable' ('UserID'))

問題是我在設置外鍵時正在設置主鍵。 這引起了問題。

因此,必須在創建表時完成主列的設置,而在創建所有相關表后必須添加外鍵。

我認為最好在創建完所有表之后創建一個create_associations遷移文件,以便此遷移具有最新的時間戳,並且在執行該文件時,所有表都已存在於數據庫中。

暫無
暫無

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

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