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.
Related
In my migration file , I am adding organization id to the user's table , i tried all of the code below but not solved yet
class AddOrganizationIdToUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
// $table->foreignId('organization_id')->references('id')->on('organizations')->onDelete('cascade');
$table->foreignId('organization_id')->constrained('organizations')->cascadeOnDelete();
// $table->foreign('organization_id')->references('id')->on('organizations')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
//
});
}
I have data on my user's table so it is giving errors while migrating, to solve it I add the field as nullable
$table->foreignId('organization_id')->nullable()->references('id')->on('organizations')->onDelete('cascade');
if you write with foreignId need:
$table->foreignId('organization_id')->constrained('organizations')->cascadeOnDelete();
or just foreign
$table->foreign('organization_id')->references('id')->on('organizations')->onDelete('cascade');
What could be the issue is that this migration is running before the organizations table migration, and when it tries to find it to create the constraint it fails.
What I would suggest is on the AddOrganizationIdToUsersTable :
Schema::table('users', function (Blueprint $table) {
$table->foreignId('organization_id');
});
And on the Organization creation migration:
Schema::table('users', function(Blueprint $table) {
$table->foreign('organization_id')->references('id')->on('organizations');
});
#2 solution:
Move the migration of Organization table to run before your AddOrganizationIdToUsersTable by changing the timestamp on the name of the file
I have a categories table that allows to have subcategories through the parent_id.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->unsignedBigInteger('parent_id')->unsigned()->nullable();
$table->string('slug');
$table->foreign('parent_id')->references('id')->on('categories');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
The problem comes when I want to delete a subcategory. I get an error when I have a foreign key.
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`doogmas`.`categories`, CONSTRAINT `categories_parent_id_foreign` FOREIGN KEY (`parent_id`) REFERENCES `categories` (`id`)) (SQL: delete from `categories` where `id` = 30)
How can I delete the record even if I have the foreign key?
Try changing this
$table->foreign('parent_id')->references('id')->on('categories');
to
$table->foreign('parent_id')->references('id')->on('categories')->onDelete('cascade');
You can set how your database handles it when you delete a row:
$table->foreign('parent_id')->references('id')->on('categories')->onDelete('cascade');
I'm trying to create foreign keys in Laravel however when I migrate my table using "artisan" I am thrown the following error and i do not know why:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215
Cannot add foreign key
constraint (SQL: alter table `positions` add constraint
`positions_car_id_foreign`
foreign key (`car_id`) references `cars` (`id`))
The table car should hava an id which is unique and to every car there are many different positions (lat and long). The car id is the foreign key.
Car migration file:
class Car extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('cars',function (Blueprint $table){
$table->integer('id')->unique();
$table->string('name');
$table->string('location');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('cars');
}
}
Postion migration file:
class Position extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('positions',function (Blueprint $table){
$table->engine = 'InnoDB';
$table->timestamps();
$table->integer('car_id')->unsigned();
$table->double('latitude');
$table->double('longitude');
});
Schema::table('positions',function (Blueprint $table) {
$table->foreign('car_id')->references('id')->on('cars');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('positions');
}
}
You have defined the foreign key relationship with cars as $table->integer('car_id')->unsigned()
So, your migration code for id field in cars table should be
$table->unsignedInteger('id')->unique() instead of $table->integer('id')->unique()
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...
I'm using laravel 5, I'm having an issue while adding a column to a table
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (homest
ead.#sql-4f4_a9, CONSTRAINT posts_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE) (SQ
L: alter table posts add constraint posts_user_id_foreign foreign key (user_id) references users (id) on delete cascade
)
The code below should work for you. I tested it in my own setup.
Make sure the posts table is deleted from your database before running this migration. Otherwise it may fail.
If it's not deleted by reversing the migration you could delete it manualy. If you do so don't forget to delete the rule from the migrations table in your database.
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ToPostTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->text('body');
$table->timestamps();
$table->timestamp('published_at');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('posts');
}
}
Make sure you have user_id in the fillable property of your Post model.
http://laravel.com/docs/5.0/eloquent#mass-assignment