【问题标题】:Add foreign key constraints in Laravel migration在 Laravel 迁移中添加外键约束
【发布时间】:2015-01-01 04:33:02
【问题描述】:

我知道很多人多次问过同样的问题,但似乎我无法为我提供相同的解决方案。

我无法为下面给出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'))

【问题讨论】:

    标签: php laravel artisan-migrate


    【解决方案1】:

    问题是我在设置外键时设置了主键。这引起了问题。

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

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

    【讨论】:

    • 或者任何你想作为外键的列,必须是索引和无符号的。所以,也试试吧。
    猜你喜欢
    • 2019-03-24
    • 2017-03-27
    • 2018-04-01
    • 2020-03-12
    • 2021-08-30
    • 2019-10-09
    • 2020-09-21
    • 2020-01-20
    相关资源
    最近更新 更多