0

多くの人が同じ質問を何度もしたことは知っていますが、同じ解決策をうまく機能させることができないようです.

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'))

4

1 に答える 1

0

問題は、外部キーの設定時に主キーを設定していたことです。これが問題を引き起こしていました。

そのため、プライマリ列の設定はテーブルの作成中に行う必要がありますが、関連するテーブルをすべて作成したら、外部キーを追加する必要があります。

create_associationsこの移行のタイムスタンプが最新になるように、すべてのテーブルが作成された後に移行ファイルを作成し、このファイルが実行されるまでにすべてのテーブルがデータベースに存在するようにする方がよいと思います。

于 2015-01-01T04:58:56.500 に答える