I have three table (Company,Branch,medicines). i want that the primary key of " Company table" and " Branch table" are foreign key in " medicines-table "
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();
});
}
But the error is occured.
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.
Possible solutions:-
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();
});
}
Make sure company
and branch
table exist.
Foreign Key like
tablename_id
is recommended.
Always use underscore (_) for the name of your foreign keys . You will thank me later.
The error occurs because you try to create the foreign key of a table before creating the foreign table. Basicaly 1 solution is if you use artisan migration , just change the date on the migrations files so the company and branch table have the oldest date in order to be created first. Or do it manually , there nothing else wrong