Laravel - Dropping foreign key and adding in one migration - php

I am trying to drop the foreign key and add the foreign key in one migration but can't get it to work:
I have created the table contents with the foreign key cms_id:
public function up()
{
Schema::create('contents', function (Blueprint $table) {
$table->increments('id');
$table->integer('ct_id')->unsigned();
$table->foreign('ct_id')->references('id')->on('content_types');
$table->integer('cms_id')->unsigned();
$table->foreign('cms_id')->references('id')->on('inventories');
$table->string('title');
$table->string('slug');
$table->text('excerpt');
$table->mediumText('body');
$table->string('password');
$table->integer('parent_id');
$table->timestamps();
});
}
This is how the inventories table looks like:
Schema::create('inventories', function (Blueprint $table) {
$table->increments('id');
$table->integer('remote_id');
$table->integer('local_id')->unsigned();
$table->string('local_type');
$table->timestamps();
});
And after failing to drop it and to create a new foreign key, I have deleted all the tables in the DB, and have tried to run all the migrations again with the new one as well, which holds this:
public function up()
{
Schema::table('inventories', function (Blueprint $table) {
$table->integer('remote_id')->unsigned()->change();
});
Schema::table('contents', function (Blueprint $table) {
$table->dropForeign('contents_cms_id_foreign');
$table->foreign('cms_id')->references('remote_id')->on('inventories');
});
Schema::table('files', function (Blueprint $table) {
$table->dropForeign('files_cms_id_foreign');
$table->foreign('cms_id')->references('remote_id')->on('inventories');
});
}
But,I get:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
(SQL : alter table contents add constraint
contents_cms_id_foreign foreign k ey (cms_id) references
inventories (remote_id))
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
If, I first run all the migrations where I create all the tables, and then after that run the new migration where I change the foreign keys, I get this error:
[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP
'content s_cms_id_foreign'; check that column/key exists (SQL:
alter table contents drop foreign key
contents_cms_id_foreign)
[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP
'content s_cms_id_foreign'; check that column/key exists
I have even tried to just delete all the tables in the DB, and only edit the files that I already have by just changing, without new migrations:
$table->integer('ct_id')->unsigned();
$table->foreign('ct_id')->references('remote_id')->on('content_types');
$table->integer('cms_id')->unsigned();
$table->foreign('cms_id')->references('remote_id')->on('inventories');
And, also in the inventories table:
$table->integer('remote_id')->unsigned();
But, even then it won't work, and I get:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
(SQL : alter table contents add constraint
contents_cms_id_foreign foreign k ey (cms_id) references
inventories (remote_id))
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
So, I have checked all of the usual suspects that I have come across on the internet, I have even added $table->engine = 'InnoDB'; to to the tables inventories, contents and files, I have made sure to first create tables and then add foreign keys, as well as checked if the columns have the same data type, not sure what to do else?

Related

Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails - Laravel

I'm getting this error, upon running php artisan migrate.
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table if exists `products`)
create_products_table.php inside migration
public function up()
{
Schema::dropIfExists('products');
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
// Other attributes here
$table->bigInteger('ctg_id')->unsigned();
$table->bigInteger('product_variation_id')->unsigned();
$table->bigInteger('sub_ctg_id')->unsigned();
$table->bigInteger('vehicle_id')->unsigned();
$table->foreign('ctg_id')->references('id')->on('ctgs')->constrained()->onDelete('cascade')->onUpdate('cascade');
$table->foreign('product_variation_id')->references('id')->on('product_variations')->constrained()->onDelete('cascade')->onUpdate('cascade');
$table->foreign('sub_ctg_id')->references('id')->on('sub_ctgs')->constrained()->onDelete('cascade')->onUpdate('cascade');
$table->foreign('vehicle_id')->references('id')->on('vehicles')->constrained()->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('products');
}
I searched online, got this solution, changed the code accordingly but in vain
https://stackoverflow.com/a/47544195/7290043
For now, I'm just working with the below tables
You must use $table->dropForeign() before deleting the table, Remove the external key to avoid this error.

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint laravel 9

Trying to assign foreign key but when you run migrate, I get this this error, I do not understand what the problem is.
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table categories add constraint categories_parent_key_foreign foreign key (parent_key) references categories (key) on delete cascade)
$table->bigIncrements('id');
$table->string('key', 64)->unique();
$table->string('parent_key', 64)->nullable()->index();
$table->string('title', 256)->index()->unique();
$table->foreign('parent_key')->references('key')
->on((new Category())->getConnection()->getDatabaseName() . '.' . Category::TABLE)
->onDelete('cascade');
I had the same problem.
The problem arises when a model has a relationship with itself (self-relation).
To solve this problem, first, the migration file must be created and then the foreign key must be assigned in another migration file.
You must remove the foreign key assignment from the migration file and create the new migration file after that, then add relations statements to assign a foreign key. (the order of the migration files is important).
create_category_table
public function up(): void
{
$table->bigIncrements('id');
$table->string('key', 64)->unique();
$table->string('parent_key', 64)->nullable()->index();
$table->string('title', 256)->index()->unique();
}
create_category_relation_table
public function up(): void
{
$table->foreign('parent_key')->references('key')
->on((new Category())->getConnection()->getDatabaseName() . '.' . Category::TABLE)
->onDelete('cascade');
}
And then php artisan migration
In my case the problem was in the different datatypes of the referenced table key and the key reference. For instance, integer(unsigned) vs bigInteger(unsigned).

Foreign keys error in migrations (Laravel 6.0)

I'm trying to figure out how migrations in Laravel work. Here you can see I'm creating 2 tables. And in the second table (RealNationalLeague), I'm having foreign keys to two columns (real_nation_id, level) in the first table (RealNationalLeagueLevel).
public function up()
{
...
Schema::create(Model\RealNationalLeagueLevel::TABLE, function (Blueprint $table) {
$table->unsignedInteger("real_nation_id");
$table->unsignedTinyInteger("level");
$table->foreign("real_nation_id")->references("id")->on(Model\RealNation::TABLE);
$table->primary(["real_nation_id", "level"]);
});
Schema::create(Model\RealNationalLeague::TABLE, function (Blueprint $table) {
$table->increments("id");
$table->unsignedInteger("real_nation_id");
$table->unsignedTinyInteger("level");
$table->string("name", 32);
$table->foreign("real_nation_id")->references("real_nation_id")->on(Model\RealNationalLeagueLevel::TABLE); // this works
$table->foreign("level")->references("level")->on(Model\RealNationalLeagueLevel::TABLE); // this does not
});
}
Running the migration does not work. It throws QueryException:
SQLSTATE[HY000]: General error: 1005 Can't create table `testdb`.`#sql-17a00_448a37` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `real_national_league` add constraint `real_national_league_level_foreign` foreign key (`level`) references `real_national_league_level` (`level`))
Any idea why it's not working? Thanks for any help.
The table that you want to reference, you have to create it first, then in another migration, create a column from this table to that reference table.

String as Primary Key in Laravel migration

I've had to change a table in my database so that the primary key isn't the standard increments.
Here's the migration,
public function up()
{
Schema::create('settings', function (Blueprint $table) {
$table->text('code', 30)->primary();
$table->timestamps();
$table->text('name');
$table->text('comment');
});
}
However, MySQL keeps returning with,
Syntax error or access violation: 1170 BLOB/TEXT column 'code' used in
key specification without a key length (SQL: alter table settings
add primary key settings_code_primary(code)
I've tried leaving the normal increments id in there and modifying the table in a different migration but the same thing happens.
Any ideas of what I'm doing wrong?
Laveral Version 5.4.23
Change it to string.
$table->string('code', 30)->primary();

laravel errno 150 foreign key constraint is incorrectly formed

Can anybody help me to solve this problem?
There are 3 tables with 2 foreign keys:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('firms', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->nullable();
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
Schema::create('jobs', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->nullable();
$table->integer('firm_id')->unsigned()->nullable();
$table->foreign('firm_id')->references('id')->on('firms');
$table->timestamps();
});
Error after running migration:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table `job`.`#sql-5fc_a1`
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter ta
ble `firms` add constraint `firms_user_id_foreign` foreign key (`user_id`)
references `users` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table `job`.`#sql-5fc_a1`
(errno: 150 "Foreign key constraint is incorrectly formed")
In case of foreign keys, the referenced and referencing fields must have exactly the same data type.
You create the id fields in both users and firms as signed integers. However, you create both foreign keys as unsigned integers, therefore the creation of the keys fail.
You need to either add the unsigned clause to the id field definitions, or remove the unsigned clause from the foreign key fields.
This answer is not better than the six answers before it but it is a more comprehensive answer on what causes laravel-errno-150-foreign-key-constraint-is-incorrectly-formed and how to fix specifically for laravel.
1) Spelling : often at times a wrong spelling of the referenced column name or referenced table name can throw up this error and you won't know as the error trace is not very descriptive.
2) Unique : the referenced column must be unique or indexed either by adding ->primary() or adding ->unique() or adding ->index() to the column definition in your migration.
3) Data type : the referenced and referencing fields must have exactly the same data type. this can not be stressed enough.
for bigincrements expected data type is bigInteger('column_name')->unsigned();
for increments expected is integer('column_name')->unsigned(); etc.
4) Remnants : when this error occurs it does not mean that the table is not migrated rather it is migrated but the foreign key columns are not set and it is not added to the migration table hence running php artisan migrate:reset will remove other tables except the faulty tables, so a manual drop of the faulty table is recommended to avoid further errors.
5) Order : this is often the most usual cause of this error the table being referenced must be created or migrated before the reference table else artisan wont find where to integrate the foreign key. to ensure an order for the migration process rename the migration file example:
Table A:2014_10_12_000000_create_users_table.php and
Table B:2014_10_12_100000_create_password_resets_table.php
This indicates that Table A will always come before Table B to change that, i will rename Table B to 2014_10_11_100000_create_password_resets_table.php now it will migrate before Table A.
6) Enable Foreign Key : if all else fails then add Schema::enableForeignKeyConstraints(); inside your function up() before your migration code example:
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::enableForeignKeyConstraints();
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
To read more see laravel foreign key and laravel migrations
Mention any more fixes that i missed in the comments thanks.
Most of the time this kind of error occurs due to the datatype mismatch on both the table.
Both primary key table & foreign key table should use same datatype and same option.
For example:
users
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
orders
Schema::create('orders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('product_id')->unsigned();
$table->foreign('product_id')->references('id')->on('products');
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamp('added_on');
});
On above example, I am trying to assign foreign key to users table from order table but I have bigInteger datatable in order table while in user table, I have simple integer. That's why it's generated this kind of error.
Also, If you have used unsigned(), nullable() etc options with primary or foreign key then you should use same at both the place.
For PHP laravel 5.8 use unsigned modifier in this format
$table->unsignedBigInteger('user_id');
drop all tables in the database and run the migration again
users
cashier refers users
student refers cashier
In addition when declaring foreign keys in laravel all tables your are referring must be on the top. In this case you can use "->unsigned()" modifier..
If the reference table primary key is in BigIcrements then Use the BigInteger for foreign key also like below
Table ATable
public function up()
{
Schema::create('a_tables', function (Blueprint $table) {
$table->bigIncrements('id');
}
}
TABLE BTable
public function up()
{
Schema::create('b_tales', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('a_tables_id')->unsigned();
$table->foreign('a_tables_id')->references('id')->on('a_tables')->onDelete('cascade');
}
}
public function up() { Schema::create('companies', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->text('address'); $table->string('tel1'); $table->string('tel2'); $table->integer('owner'); $table->unsignedBigInteger('access_id'); $table->string('depot_number')->default(2); $table->timestamps(); $table->foreign('access_id')->references('id')->on('accesses') ->onDelete('cascade'); }); }
public function up() { Schema::create('accesses', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('type'); $table->string('description'); $table->timestamps(); }); }
In your database/migrations folder, sort by name. Then make sure create_accesses_table is before create_companies_table here:
we are table villes:
Schema::create('villes', function (Blueprint $table) {
$table->bigIncrements('idVille'); // bigIncrement(8 bits)
$table->string('nomVille');
$table->timestamps();
});
foreign key in table users for exemple :
Schema::table('users', function (Blueprint $table) {
$table->bigInteger('ville_idVille')->unsigned()->after('tele');
$table->foreign('ville_idVille')->references('idVille')->on('villes');
});
if you set referencing fields and be have exactly the same data type but error exists
you can change date migration file
just its working
I tried all the answers provided in this thread.
Nothing worked.
Then I discovered I forgot to remove the "migrations" table in phpMyadmin.
I removed all tables from phpMyAdmin but the migrations table. That's why the error persisted again and again.
Well this answer is related to Laravel 7.x. So the error:
errno: 150 "Foreign key constraint is incorrectly formed"
can occur due many reason while migrating the migrations. The one common reason that I am familiar about is order of migration.
Lets say we have two table "users" and "roles", and "users" table have a foreign key referring the "id" column on "roles" table. So make sure that "roles" is migrated before "users" table.
So order of migration is important. Its obvious as it does not make sense for MySQL to refer to "id" column of unknown table.
Second reason is wrong data type. In laravel 7.x we use "id()" method for primary key. So make sure that the intended foreign key (in my case "role_id" in "users" table) is of "bigInteger" and is "unsigned".
Here my code:
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->nullable();
$table->timestamps();
});
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->bigInteger("role_id")->unsigned();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
public function down()
{
Schema::table('users', function(Blueprint $table)
{
$table->dropForeign('users_role_id_foreign');
});
Schema::dropIfExists('users');
}
So in the above code I had to migrate the "roles" table first then the "users" table. So MySQL can create foreign key for the roles table.
What is do is I move the child migration (migration having foreign key) to temporary folder. And restore it after migrating parent migration (in my case "roles" table and then migrate the child migration ("users" migration).
And as side tip: while dropping the dependent migration (migration containing foreign key) first drop the foreign key first. And Laravel uses specific naming convention while dropping foreign key "<table_name>_<foreign_key>_foreign".
So happy coding and be ready for Ground breaking release of PHP 8.
Here the main concept is you have to ensure same type of primary key and foreign key. For example, Let your 1st table migration is
public function up()
{
Schema::create('chapters', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->timestamps();
});
}
Then your 2nd table migration will be
public function up()
{
Schema::create('classifications', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->unsignedBigInteger('chapter_id');
$table->timestamps();
$table->foreign('chapter_id')->references('id')->on('chapters')->onDelete('cascade');
});
}
Here "id" in "chapter" table and "chapter_id" in " classifications " table are same and that is "unsignedBigInteger".
Again if you get error then change " $table->id(); " in "chapter" table by " $table->bigIncrements('id'); ".
Hope this will help you
for the laravel 7 migration error as
("SQLSTATE[HY000]: General error: 1005 Can't create table laraveltesting.reviews (errno: 150 "Foreign key constraint is incorrectly formed")")
order of migration is most important so parent table should be migrated first then only child
Image 1:migration order while getting error
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('detail');
$table->float('price');
$table->integer('stock');
$table->float('discount');
$table->timestamps();
});
Schema::create('reviews', function (Blueprint $table) {
$table->id();
$table->foreignId('product_id')->constrained('products')->cascadeOnDelete();
$table->string('customer');
$table->text('review');
$table->integer('star');
$table->timestamps();
});
this causes the error while migrating this can be resolved by changing the order of migration by renaming the migration as shown in image 2 from the image 1. books table should be migrated first then only the review table should be migrated
Image 2:Order of migration for the successful migration
if you get error change $table->id()(references) by $table->increments('id')
worked with me after all Efforts
delete (user table) from both database and (migration table) then "uncomment" your foreign key Relations
example :
$table->string('pass1');
$table->foreign('pass1')->references('email')->on('abs');
then run : php artisan migrate
well run successfully
sometime your query syntax is true but this error is occur because you create your table unorderly if you want to make relation between table let's suppose you wanna a create many to many relationship between "user" and "role" table for this you should migrate user and role table first then create "role_user" table else you face error like this.
For more details check my screenshot.
enter image description here
in laravel 9 i got same error while creating foreign key for my posts table
SQLSTATE[HY000]: General error: 1005 Can't create table `wpclone`.`posts` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `posts` add constraint `posts_author_id_foreign` foreign key (`author_id`) references `users` (`id`) on delete restrict)
and my table looks like this:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->integer('author_id')->unsigned();
$table->foreign('author_id')->references('id')->on('users')->onDelete('restrict');
$table->string('title');
});
after i found solution that in laravel 9 unsigned modifier in this format work well
$table->unsignedBigInteger('author_id');
and my error was solve. hope this will help you. Thanks

Categories