Laravel 5.2 rollback database with foreign key - laravel

I'm trying to rollback my database, but have this error:
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table tb_levels)
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or update a parent row: a foreign key constraint fails
this is my migration code:
public function up()
{
Schema::disableForeignKeyConstraints();
Schema::create('tb_users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id_user');
$table->string('name');
$table->string('username');
$table->string('email')->unique();
$table->integer('id_level')->unsigned();
$table->string('password', 60);
$table->rememberToken();
$table->boolean('activated')->default(false);
$table->timestamps();
$table->foreign('id_level')->references('id_level')->on('tb_levels');
});
Schema::enableForeignKeyConstraints();
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::table('tb_users', function(Blueprint $table){
$table->dropForeign('tb_users_id_level_foreign');
$table->dropColumn('id_level');
});
Schema::drop('tb_users');
Schema::enableForeignKeyConstraints();
}
I've tried several ways that I found in this forum, but still got that error, any help please?

First Disable Foreign Key using this:
SET FOREIGN_KEY_CHECKS=1;
SET GLOBAL FOREIGN_KEY_CHECKS=1;
And then migrate your database.
Again Apply Foreign key constrain:
SET FOREIGN_KEY_CHECKS=0;
SET GLOBAL FOREIGN_KEY_CHECKS=0;

Well, finally I found a way to solve that error,
First of all you need to make a migration to drop the foreign key and column, this is the code:
public function up()
{
Schema::disableForeignKeyConstraints();
Schema::table('tb_users', function(Blueprint $table){
$table->dropForeign('tb_users_id_level_foreign');
$table->dropColumn('id_level');
});
Schema::enableForeignKeyConstraints();
}
Then migrate it, after that It will drop the column and foreign key.
After that delete Schema::table code, save it, and run command:
php artisan migrate:reset
Well, It works but it's really an impractical way,
Hope that out there had more easy way rather than this.

Related

Foreign Key problem when migrating migrations in laravel 5.6

Am working on a Laravel 5.6 application whereby I have 2 tables mainly sponsors table and children table. Am creating a one to many relationship between the tables before migrating them. A child may have many sponsors.
The problem is I get this error when migrating them using php artisan migrate command:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error:
1005 Can't create table larangular.#sql-520c_21f (errno: 150
"Foreign key constraint is incorrectly formed") (SQL: alter table
sponsors add constraint sponsors_child_id_foreign foreign key
(child_id) references children (id) on delete cascade)
Sponsors migration
public function up()
{
Schema::create('sponsors', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('child_id')->unsignedInteger();
$table->foreign('child_id')->references('id')->on('children')->onDelete('cascade');
$table->foreign('child_id')->references('id')->on('children');
$table->string('email')->unique();
$table->string('phone');
$table->string('nationality');
$table->timestamps();
});
}
Children migration
public function up()
{
Schema::create('children', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('age');
$table->string('gender');
$table->timestamps();
});
}
Make sure that your children migration runs before your sponsors migration, and then the column should be this:
$table->unsignedInteger('child_id');
// or
$table->integer('child_id')->unsigned();
unsignedInteger is a function that creates a column, you should not call it on an existing column.
// This creates an unsigned integer column.
$table->unsignedInteger('child_id');

Laravel 5.4 - Error dropping unique constraint on foreign key [duplicate]

This question already has an answer here:
Drop muli-column unique key without dropping foreign key?
(1 answer)
Closed 4 years ago.
I'm trying to drop a unique constraint and I keep running into a foreign key constraint issue:
Here's the original migration:
Schema::table('table', function (Blueprint $table) {
$table->bigInteger('other_table_id')->unsigned()->unique()->nullable();
$table->foreign('other_table_id')->references('id')->on('other_table')->onDelete('set null');
});
Fast forward to now, I'm trying to drop the UNIQUE constraint from the column on the table without affecting the foreign key.
Schema::table('table', function (Blueprint $table) {
$table->dropUnique('table_other_table_id_unique');
});
Here's the error I'm getting.
SQLSTATE[HY000]: General error: 1553 Cannot drop index 'table_other_table_id_unique': needed in a foreign key constraint
I've also tried using
Schema::table('table', function (Blueprint $table) {
$table->dropUnique(['other_table_id']);
});
But that didn't work either.
I even tried disabling the foreign key constraint while doing the migration:
Schema::disableForeignKeyConstraints(); // Disable constraint
Schema::table('table', function (Blueprint $table) {
$table->dropUnique(['other_table_id']);
});
Schema::enableForeignKeyConstraints(); // Reenable constraint
Nothing seems to work. What am I doing wrong?
The link Joel Hinz had commented was enough information to answer my question. I'm answering my own question since I can provide the answer with code specific to Laravel.
The issue stemmed from the foreign key using the unique key as its key. Therefore, the foreign key must be dropped before dropping the unique key, then set up the foreign key again.
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('table', function (Blueprint $table) {
$table->dropForeign(['other_table_id']);
$table->dropUnique(['other_table_id']);
$table->foreign('other_table_id')->references('id')->on('other_table')->onDelete('set null');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('table', function (Blueprint $table) {
$table->unique('other_table_id');
});
}

Laravel:Can't drop foreign key even using 'dropForeign' method

I'm about to refresh my migration. But php artisan migrate:refresh command is not working.
It shows the following error:
[Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error
or access violation: 1091 Can't DROP 'classes_userid_foreign'; check
that column/key exists (SQL: alter table classes drop foreign key
classes_userid_foreign)
[PDOException] SQLSTATE[42000]: Syntax error or access violation:
1091 Can't DROP 'classes_userid_foreign'; check that column/key
exists
I even used the dropForeign but its not working for me.
I'm showing my migration file
public function up()
{
Schema::create('classes', function (Blueprint $table) {
$table->increments('id');
$table->integer('userId')->unsigned();
$table->string('title');
$table->string('name');
$table->string('code')->unique();
$table->integer('capacity')->unsigned();
$table->integer('tagId')->unsigned();
$table->foreign('userId')->references('id')->on('users');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('classes', function (Blueprint $table) {
$table->dropForeign(['userId']);
});
Schema::drop('classes');
}
How to fix this problem ?
Most times when you run migrations in laravel (whether up or down), and an error occurs along the line, the transaction may have completed partially without registering it in the migrations table.
If this is the case, or you will like to drop tables whether or not there really exists a foreign key, then you should consider disabling foreign key checks like so:
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::drop('classes');
Schema::enableForeignKeyConstraints();
}

Laravel create simple relationship for 2 table from single table

I have 3 models: User , ChangeMoney and CurrencyType, I have simple relationship with User and ChangeMoney and I want to add another relationship with ChangeMoney table with CurrencyType, but I get this error:
D:\xampp\htdocs\epay-pro>php artisan migrate
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `change_money` add constraint change_money_currency_id_foreig
n foreign key (`currency_id`) references `currency_type` (`id`))
current my migration is:
Schema::create('change_money',function(Blueprint $table){
$table->increments('id');
$table->tinyInteger('currency_type');
$table->string('current_money');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('currency');
$table->timestamps();
});
and I don't have any problem, now I want to add other foreign key to CurrencyType table such as:
Schema::create('change_money',function(Blueprint $table){
$table->increments('id');
$table->tinyInteger('currency_type');
$table->string('current_money');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('currency_id')->unsigned();
$table->foreign('currency_id')->references('id')->on('currency_type');
$table->timestamps();
});
currency_type table migration:
Schema::create('currency_type',function(Blueprint $table){
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('currency_type','50');
$table->char('currency_symbol','1');
$table->timestamps();
});
Migrations in Laravel runs in order. I don't now your migrations order, but I think that your change_money migration is running first than your currency_type migration. So when the aplication try to add a foreign key in ChangeMoney table to CurrencyType table, the CurrencyType table not exist yet.
Try to create a new migration to add just the relationship between ChangeMoney table and CurrencyType table
You have to remove data from both tables ('change_money', 'currency_type').
Or you can turn off the check of foreign keys. In MySQL, or in the phpmyadmin run this:
SET FOREIGN_KEY_CHECKS=0;
Run migration in Laravel: php artisan migrate
And then again turn on check of foreign keys:
SET FOREIGN_KEY_CHECKS=1;
PROBLEM SOLVED by split foreign key to other migration
class ForeignKeyBetweenChangeMoneyAndCurrencyType extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('change_money', function (Blueprint $table) {
$table->integer('currency_id')->unsigned();
$table->foreign('currency_id')->references('id')->on('currency_type');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('change_money', function(Blueprint $table) {
$table->dropForeign(' change_money_currency_id_foreign');
});
}
}

Laravel migration won't reference second foreign key

I am trying to reference the id of a product on two tables (a categories and a brands table).
public function up()
{
Schema::create('products', function($table)
{
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->integer('brand_id')->unsigned();
$table->string('title');
$table->text('description');
$table->decimal('price', 6, 2);
$table->boolean('availability')->default(1);
$table->string('image');
$table->timestamps();
});
Schema::table('products', function($table){
$table->foreign('category_id')->references('id')->on('categories');
$table->foreign('brand_id')->references('id')->on('brands');
});
}
But I get the following errors:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `products` add constraint products_brand_id_foreign foreign k
ey (`brand_id`) references `brands` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
Which is the correct way to do this?
Update
Migration public function up for the brands table
public function up()
{
Schema::create('brands', function($table){
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
Solution
Finally, the error was on the naming of the migration. Due to the fact that brands table was the most recent table I had to changed its name from: 2014_12_12_164325_create_brands_table to this 2014_10_12_164325_create_brands_table and the tables were migrated successfully.
Everything looks ok to me. Furthermore, since it only complains about the second part, the categories foreign key must've worked. I would think the brands table doesn't exist or there is something wrong there. Does the table exist and does it have a primary key "id"?
I also use
$table->engine = 'InnoDB';
at the beginning, because MyISAM doesn't support foreign keys as of now. I don't think it should be an issue in the above case, but perhaps still advisable, if you want to do foreign key restrictions on the DB level.

Resources