一般错误:1005无法创建表错误:150"外键约束形成错误")

时间:2017-08-26 15:04:26

标签: php database laravel phpmyadmin laravel-5.4

  

块引用   SQLSTATE [HY000]:常规错误:1005无法创建表gps#sql-9e4_161(错误:150"外键约束形成错误")(SQL:alter table receivers添加约束 receivers_hospital_id_foreign外键(hospital_id)引用hospitalsid))

{
    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 :(得分:0)

我没有看到memberblood_groups表来全面检查所有内容。

检查

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

2)确保订单正确。如果没有表,则无法创建外键。对于代码,我认为它应该像

另外,我发现在hospitals表中你有FK(country_id)到countries表,在countries表中你有FK({{1} })到hospital_id表。你不能这样做,应该只有一个(可能是hospitals)。原因是因为(我不知道哪一个是先创建的,所以说它是country_id)当你创建hospitals时,你试图让FK到不存在的表。