【问题标题】:Foreign key constraint error when adding through migrating通过迁移添加时外键约束错误
【发布时间】:2013-11-19 18:51:11
【问题描述】:

我正在尝试在 Laravel 4 上的两个表 User 和 GP 之间创建外键约束。一个用户可以与多个 GP 相关联。外键是users表中的'Practice_ID',与GP表中的ID相关联。

    public function up()
{

    // Creates GP table
    Schema::create('gp', function($ta)
    {
        $ta->bigIncrements('id');
        $ta->string('address_1');
        $ta->string('address_2');
        $ta->string('address_3');
        $ta->string('post_code');
        $ta->timestamps();
    });

    // Creates the users table
    Schema::create('users', function($table)
    {
        $table->increments('id');
        $table->string('username');
        $table->string('email');
        $table->string('password');
        $table->string('confirmation_code');
        $table->boolean('confirmed')->default(false);
        $table->bigInteger('practice_id');
        $table->foreign('practice_id')->references('id')->on('gp');
        $table->timestamps();
    });

    // Creates password reminders table
    Schema::create('password_reminders', function($t)
    {
        $t->string('email');
        $t->string('token');
        $t->timestamp('created_at');
    });

}

我得到的错误是:

[例外]
SQLSTATE[HY000]:一般错误:1005 无法创建表 'doctor.#sql-3ac_a4' (errno: 150) (SQL: alter table users add 约束 users_practice_id_foreign 外键 (practice_id) 参考gp (id)) (绑定: 数组 (
))

【问题讨论】:

    标签: foreign-keys migration laravel-4


    【解决方案1】:

    err 150 很可能是数据类型不匹配。

    将 users 表中的外键删除为无符号整数:

    $table->integer('practice_id')->unsigned();
    

    还要验证您的数据库引擎是支持 FK 约束的 INNODB

    【讨论】:

    • 嗨,A.O,我已经进行了调整(参见上面的修改代码),但是,在 php artisan migrate:refresh 上,仍然出现相同的错误。
    • 在 gp 表中将其改回普通的increments 并在用户表中尝试上述代码
    猜你喜欢
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 2014-05-02
    • 1970-01-01
    • 2016-03-03
    • 2019-03-24
    相关资源
    最近更新 更多