I have a problem with my Laravel migrations :(
when i'm running php artisan migrate, it stops on a foreign key.
first migration
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::enableForeignKeyConstraints();
Schema::create('fichefrais', function (Blueprint $table) {
$table->char('idVisiteur', 4);
$table->foreign('idVisiteur')->references('id')->on('visiteur');
$table->char('mois',6);
$table->primary(['idVisiteur', 'mois']);
$table->integer('nbJustificatifs');
$table->decimal('montantValide', 10, 2);
$table->date('dateModif');
$table->char('idEtat', 2);
$table->foreign('idEtat')->references('id')->on('etat');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('fichefrais');
}
and the second
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::enableForeignKeyConstraints();
Schema::create('lignefraishorsforfait', function (Blueprint $table) {
$table->integer('id');
$table->primary('id');
$table->char('idVisiteur', 4);
$table->char('mois',6);
$table->foreign('idVisiteur')->references('idVisiteur')->on('fichefrais');
$table->foreign('mois')->references('mois')->on('fichefrais');
$table->char('libelle', 100);
$table->date('date');
$table->decimal('montant', 10, 2);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('lignefraishorsforfait');
}
After running the command, I got this error :
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table
gsb_larave.#sql-176_b9 (errno: 150 "Foreign key constraint is
incorrectly formed") (SQL: alter table lignefraishors forfait
add constraint lignefraishorsforfait_mois_foreign foreign key
(mois) references fichefrais (mois) on delete cascade on update
cascade)
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table
gsb_laravel.#sql-176_b9 (errno: 150 "Foreign key constraint is
incorrectly formed")
Does your visiteur table has an id as a primary key? If yes, does it have a data type has char and a length of 4. The idVisiteur in ** lignefraishorsforfait** table has a data type of char which must be the same as the primary key in the visiteur table.
The problem is that the foreign key you are declaring doesn't refer to a primary key. If you want to create a foreign key to a non-primary key, the column 'mois' in your 'fichefrais' table must be a column with a unique constraint on it
First of all your foreign keys must refer to a primary key (which most of the time is 'id' column).
Also you should create the tables in this order:
1- 'etat' table(which i dont see bcs you did not posted the migration code,),
2- 'fichefrais' table,
3- 'lignefraishorsforfait' table.
Just change the dates on database/migrations like this (example):
2020_09_11_150331_create_etat_table.php
2020_09_12_000000_create_fichefrais_table.php
2020_09_13_000000_create_lignefraishorsforfait_table.php
You cannot create first the table which contains foreign key because will not have a key in which to refer.
Use this migrations:
First migration (fichefrais):
public function up()
{
Schema::create('fichefrais', function (Blueprint $table) {
$table->integer('idVisiteur')->unsigned()->nullable();
$table->foreign('idVisiteur')->references('id')->on('visiteur');
$table->char('mois',6);
$table->primary(['idVisiteur', 'mois']);
$table->integer('nbJustificatifs');
$table->decimal('montantValide', 10, 2);
$table->date('dateModif');
$table->integer('idEtat')->unsigned()->nullable();
$table->foreign('idEtat')->references('id')->on('etat');
});
}
Second migration (lignefraishorsforfait):
public function up()
{
Schema::create('lignefraishorsforfait', function (Blueprint $table) {
$table->integer('id');
$table->primary('id');
$table->integer('mois')->unsigned()->nullable();
$table->foreign('mois')->references('mois')->on('fichefrais');
$table->integer('idVisiteur')->unsigned()->nullable();
$table->foreign('idVisiteur')->references('idVisiteur')->on('fichefrais');
$table->char('libelle', 100);
$table->date('date');
$table->decimal('montant', 10, 2);
});
}
You are using MySQL, so Are your tables defined in InnoDB engine? MyISAM doesn't accept foreign key...
Related
In my migration operation I intend to create two tables: hunter and master, the table master contains the foreign key of hunter. When running php artisan migrate the following error occurs: SQLSTATE[HY000]: General error: 1005 Can't create table teste.master (errno: 150 "Foreign key constraint is incorrectly formed")
(SQL: alter table master add constraint master_id_hunter_foreign foreign key (id_hunter) references id_hunters (id)), I don't understand what mistake i'm making.
Not to mention that when using php migration:rollback the master and migrations tables is not deleted.
Migration hunter
public function up()
{
Schema::create('hunter', function (Blueprint $table) {
$table->id('id_hunter');
$table->string('name_hunter', 50);
$table->integer('age_hunter');
$table->decimal('weight_hunter', 5,2);
$table->decimal('heigth_hunter', 3,2);
$table->string('type_hunter', 30);
$table->string('nen_hunter', 30);
$table->string('type_blood', 3);
$table->timestamp('date_insert')->useCurrent();
$table->timestamp('date_update')->useCurrent()->useCurrentOnUpdate();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('hunter');
}
Migration master
public function up()
{
Schema::create('master', function (Blueprint $table) {
$table->id('id_master');
$table->foreignId('id_hunter')->constrained();
$table->string('name_master', 50);
$table->string('nen_master', 30);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('master');
}
add this to inside you master migration
$table->foreign('id_hunter')->references('id_hunter')->on('hunter')->onDelete('cascade');
In the migrate hunter file:
$table->id(); // Removed 'id_hunter'
In the migrate master file:
$table->id(); // Removed 'id_master'
$table->foreignId('id_hunter')->constrained('hunter'); // Added ´hunter´ in constrained()
public function up()
{
Schema::create('company_eligibilities', function (Blueprint $table) {
$table->id();
$table->string('marks');
$table->integer('company_id')->unsigned();
$table->timestamps();
$table->foreign('company_id')
->references('id')->on('companies')
->onDelete('cascade')
->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('company_eligibilities');
}
Company migration already did before executing the above migration
I am getting the above error when I am trying to create a table along with the foreign key. Have I done something wrong ??
Make sure that, you migrate companies before migrate company_eligibilities, change your foreign key id to
unsigned big integer, Laravel 5.8 make default foreign key as unsigned big integer, also for 6.x and 7.x :
$table->bigInteger('company_id')->unsigned();
Or,
$table->unsignedBigInteger('company_id');
Trying to migrate a file but keep getting:
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table permission_role add constraint permission_role_permission_id_foreign foreign key (permission_id) references permissions (id) on delete cascade)
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddForeignKeys extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
//
Schema::table('permission_role', function(Blueprint $table) {
$table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
Schema::table('role_user', function(Blueprint $table){
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
}
}
First you should separate all your migrations. Make sure you create the roles,users and permissions tables first (each one should have it's own migration). And then proceed creating the other ones.
error: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table permission_role add constraint permission_role_permission_id_foreign foreign key (permission_id) references permissions (id) on delete cascade)
This error is occuring because the permissions table have not been created yet, so you can't reference it in your foreign key.
I'm trying to create foreign keys in Laravel however when I migrate my table using artisan i am thrown the following error:
λ php artisan migrate
Migration table created successfully.
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `fees` add constraint `fee
s_fee_type_id_foreign` foreign key (`fee_type_id`) references `feetypes` (`fee_type_id`))
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
My migration code is as so:
fees
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFeesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('fees', function (Blueprint $table) {
$table->increments('fee_id');
$table->integer('academic_id')->unsigned();
$table->integer('level_id')->unsigned();
$table->integer('fee_type_id');
$table->string('fee_heading', 100)->nullable();
$table->float('amount', 8, 2);
$table->foreign('academic_id')->references('academic_id')->on('academics');
$table->foreign('level_id')->references('level_id')->on('levels');
$table->foreign('fee_type_id')->references('fee_type_id')->on('feetypes');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('fees');
}
}
fesstypes
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFeetypesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('feetypes', function (Blueprint $table) {
$table->unsignedinteger('fee_type_id');
$table->string('fee_type', 100);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('feetypes');
}
}
Any ideas as to what I've done wrong, I want to get this right now, as I've got a lot of tables I need to create e.g. Users, Students, Leves, etc. Ideally I want to create tables which hold this data with the foreign keys, i..e fees and feetypes.
Hope someone can help me to get started.
Replace this line:
$table->integer('fee_type_id');
With this:
$table->unsignedInteger('fee_type_id');
In CreateFeesTable Migration.
Check all data types matches for the referenced data types.
public function up()
{
Schema::create('fees', function (Blueprint $table) {
$table->increments('fee_id');
$table->unsignedInteger('academic_id');
$table->unsignedInteger('level_id');
$table->unsignedInteger('fee_type_id');
$table->string('fee_heading', 100)->nullable();
$table->float('amount', 8, 2);
$table->foreign('academic_id')->references('academic_id')->on('academics');
$table->foreign('level_id')->references('level_id')->on('levels');
$table->foreign('fee_type_id')->references('fee_type_id')->on('feetypes');
});
}
check level_id in levels , academic_id in academics ,fee_type_id in feetypes are also unsignedInteger or autoincrement and change your table creating script to above one.
CreateFeesTable.php
change
$table->integer('fee_type_id');
to
$table->unsignedInteger('fee_type_id');
CreateFeetypesTable
change
$table->unsignedinteger('fee_type_id');
to
$table->increments('fee_type_id'); or
$table->integer('fee_type_id');
You must first create an index on the referenced column, i.e. fee_type_id in feetypes table.
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.
From MySQL Reference Manual
Hello I am practicing Laravel now and I'm doing some migration but when I try to run my migration I got this following errors.
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
sample.#sql-1d0c_20f, CONSTRAINT products_product_type_id_foreign FOREIGN KEY (product_type_id) REFERENCE
S product_types (id) ON DELETE CASCADE) (SQL: alter table products add constraint products_product_type_id_foreig
n foreign key (product_type_id) references product_types (id) on delete cascade)
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
sample.#sql-1d0c_20f, CONSTRAINT products_product_type_id_foreign FOREIGN KEY (product_type_id) REFERENCE
S product_types (id) ON DELETE CASCADE)
this is my my product_types migration code
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('product_types', function (Blueprint $table) {
$table->increments('id');
$table->string('product_type')->unique();
$table->tinyInteger('status')->nullable(false); //1 for active 2 for inactive
$table->timestamps('created_at');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('product_types');
}
Adding FK constrain in product table
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
/**
* Drop column type in products table
*/
Schema::table('products', function (Blueprint $table) {
$table->dropColumn('type');
});
/**
* Create column product_type in products table
*/
Schema::table('products', function (Blueprint $table) {
$table->integer('product_type_id')->unsigned()->after('price');
$table->foreign('product_type_id')->references('id')->on('product_types')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
/**
* Drop column product_type_id in products table
*/
Schema::table('products', function (Blueprint $table) {
$table->dropForeign('product_type_id');
$table->dropColumn('product_type_id');
});
/**
* Re-create column type in products table
*/
Schema::table('products', function (Blueprint $table) {
$table->string('type')->after('price');
});
}
Try changing the migrations order, being sure product_types is before product table.