Php 在Laravel迁移中添加外键约束

Php 在Laravel迁移中添加外键约束,php,laravel,artisan-migrate,Php,Laravel,Artisan Migrate,我知道很多人问过很多次同样的问题,但似乎我无法让同样的解决方案对我有效 我无法为下面给出up的相关表设置外键: //Migrate 1 Starts public function up() { Schema::create("UserTable", function($table){ $table->tinyInteger("ApplicationID"); $table->bigInteger("UserID"); $tab

我知道很多人问过很多次同样的问题,但似乎我无法让同样的解决方案对我有效

我无法为下面给出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]:常规错误:1215无法添加外键约束SQL:alter table“Membership”添加约束成员身份\u userid\u外键“userid”引用“UserTable”“userid”

问题是我在设置外键时正在设置主键。这造成了问题

因此,必须在创建表时设置主列,而在创建所有相关表后必须添加外键


我想最好在创建所有表之后创建一个create_associations迁移文件,以便此迁移具有最新的时间戳,并且在执行此文件时,所有表都已存在于数据库中。

或任何要作为外键的列都必须是索引且未签名的。那么,也试试吧。