2017-02-25 150 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遷移,只需更改遷移文件的日期,以便公司和分支表具有最早的日期以便首先創建。或者手動執行,沒有其他錯誤

相關問題