首页 文章

常规错误:1005无法创建表错误:150“外键约束形成错误”)

提问于
浏览
0

Blockquote SQLSTATE [HY000]:常规错误:1005无法创建表格gps . #sql-9e4_161(错误号码:150“外键约束形成错误”)(SQL:alter table receivers add constraint,receiver_hospital_id_foreign foreign key(hospital_id)references医院(id))

{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamp('dob');
        $table->string('profile_image');
        $table->string('profession')->nullable();
        $table->string('email')->unique();
        $table->string('weight');
        $table->string('message');
        $table->rememberToken();
        $table->timestamps();
        $table->softDeletes();

    });


{
    Schema::create('receivers', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('member_id')->unsigned()->index();
        $table->integer('hospital_id')->unsigned()->index();
        $table->timestamps();
        $table->softDeletes();
        $table->foreign('member_id')->references('id')->on('members');
        $table->foreign('hospital_id')->references('id')->on('hospitals');
    });


{
    Schema::create('hospitals', function (Blueprint $table) {
        $table->increments('id');
        $table->string('h_name');
        $table->integer('country_id')->unsigned()->index();
        $table->integer('donate_id')->unsigned()->index();
        $table->softDeletes();
        $table->timestamps();
        $table->foreign('country_id')->references('id')->on('countries');
        $table->foreign('donate_id')->references('id')->on('donates');


    });


{
    Schema::create('donates', function (Blueprint $table) {
        $table->increments('id');
        $table->date('date');

        $table->date('last_bleed');
        $table->string('quantity');
        $table->string('comments');
        $table->integer('blood_group_id')->unsigned()->index();
        $table->integer('member_id')->unsigned()->index();

        $table->timestamps();
        $table->softDeletes();
        $table->foreign('blood_group_id')->references('id')-
                             >on('blood_groups');
        $table->foreign('member_id')->references('id')->on('members');
        $table->timestamps();
    });

}

1 回答

  • 0

    我没有看到 memberblood_groups 表来全面检查一切 .

    检查一下

    1)所有外键应匹配它们匹配的主键类型 . 例如,如果您使用 increments 进行PK,请确保FK的类型为 unsignedInteger

    2)确保订单正确 . 如果没有表,则无法创建外键 . 对于代码,我看它应该是这样的

    另外,我发现在 hospitals 表中你有FK( country_id )到 countries 表,而在 countries 表中你有FK( hospital_id )到 hospitals 表 . 你不能这样做,应该只有一个(可能是 country_id ) . 原因是因为(我不是't know which of those are created first, so let say it' s hospitals ),当您创建 hospitals 时,您尝试将FK设置为不存在的表 .

相关问题