2017-02-25 153 views
0

我有三个表(公司,分公司,药品)。我想,“公司表”和“分支表”的主键是在“药品表”一般错误:1215无法添加外键约束laravel 5.3

class CreateMedicinesTable extends Migration 
{ 
    /** 
    * Run the migrations. 
    * 
    * @return void 
    */ 
    public function up() 
    { 
     Schema::create('medicines', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->Integer('company-id')->unsigned(); 
      $table->foreign('company-id')->references('company')->on('id'); 
      $table->Integer('branch-id')->unsigned(); 
      $table->foreign('branch-id')->references('branch')->on('id'); 
      $table->string('name'); 
      $table->string('type'); 
      $table->string('potency'); 
      $table->timestamps(); 
     }); 
    } 

外键但错误发生。

Illuminate\Database\QueryException]           
    SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL 
    : alter table `medicines` add constraint `medicines_company_id_foreign` for 
    eign key (`company-id`) references `id` (`company`))       



     [PDOException]               
     SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint. 
+0

默认情况下是否将表引擎设置为'InnoDB'? –

+0

不,我不知道。如何将表引擎设置为InnoDB? – Haider

+0

将表引擎添加到'InnoDB'作为'MyIsam'不支持关系数据库。 –

回答

0

可能的解决方案: -

public function up() 
{ 
    Schema::create('medicines', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('company-id')->unsigned(); //Change here like this 
     $table->foreign('company-id')->references('id')->on('company'); //Change here like this 
     $table->integer('branch-id')->unsigned(); //Change here like this 
     $table->foreign('branch-id')->references('id')->on('branch'); //Change here like this 
     $table->string('name'); 
     $table->string('type'); 
     $table->string('potency'); 
     $table->timestamps(); 
    }); 
} 

确保companybranch表中存在。

Foreign Key like tablename_id is recommended.

+0

谢谢你的帮助。 – Haider

+0

现在工作吗? –

+0

是的,它确实工作。 – Haider

0

总是使用下划线(_)作为外键的名称。你以后会感谢我。

发生该错误是因为您在创建外表之前尝试创建表的外键。 Basicaly 1解决方案是,如果您使用artisan迁移,只需更改迁移文件的日期,以便公司和分支表具有最早的日期以便首先创建。或者手动执行,没有其他错误

相关问题