Laravel Integrity constraint violation on db migration - laravel

SQLSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table `users`)
I know this has been answered several times, but still i cant figure our whats wrong with my migration.
First i call the partner migration
public function up()
{
Schema::create('partners', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('admin_id')->unsigned();
$table->string('company_name', 50);
...
}
public function down()
{
Schema::drop('partners');
}
Then i call the Users migration
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('partner_id')->unsigned();
$table->string('email', 70)->unique();
$table->string('first_name', 50);
$table->string('last_name', 50);
$table->string('password', 60);
$table->string('image', 200)->nullable();
$table->string('gender', 10)->nullable();
$table->string('phone', 25)->nullable();
$table->string('nationality', 50)->nullable();
$table->string('address', 200)->nullable();
$table->boolean('is_active')->default(0);
$table->string('single_signon', 30)->nullable();
// Checks if mysql or mariadb supports json data type
if ((DB::connection()->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') && version_compare(DB::connection()->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION), '5.7.8', 'ge')) {
$table->json('settings')->nullable();
} else {
$table->text('settings')->nullable();
}
$table->softDeletes();
$table->rememberToken();
$table->timestamps();
$table->foreign('partner_id')->references('id')->on('partners')->onDelete('cascade');
});
}
public function down()
{
Schema::table('users', function(Blueprint $table) {
$table->dropForeign('users_partner_id_foreign');
});
Schema::drop('users');
}
Last i call the notification migration:
public function up()
{
Schema::create('notifications', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('notification_type', 10);
// Checks if mysql or mariadb supports json data type
if ((DB::connection()->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') && version_compare(DB::connection()->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION), '5.7.8', 'ge')) {
$table->json('notification')->nullable();
} else {
$table->text('notification')->nullable();
}
$table->boolean('seen');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
public function down()
{
Schema::table('notifications', function(Blueprint $table) {
$table->dropForeign('notifications_user_id_foreign');
});
Schema::drop('notifications');
}
Can anybody figure out whats wrong with this? i am using laravel 5.3 and php7

The issue is in migration order. It's better to include the migrations in one file and drop the child before the parent, like this:
public function down(){
Schema::drop('notifications');
Schema::drop('users');
Schema::drop('partners');
}
That's because Laravel tries to drop users table before notifications table, which include user_id column that has reference in users table.

public function down()
{
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
Schema::drop('tableName');
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}
disable foreign key check while droping the table

Related

Laravel - How to add foreign key reference to already existing migration

In my Larave-8, I created a table using this migration:
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id');
$table->string('first_name',50);
$table->string('last_name',50);
$table->string('other_name',50)->nullable();
$table->string('gender',20);
$table->string('user_photo',350)->nullable();
$table->integer('nationality_id');
$table->string('marital_status',50);
$table->date('dob')->nullable();
$table->string('address', 300)->nullable();
$table->integer('country_id')->nullable();
$table->integer('state_id')->nullable();
$table->integer('city_id')->nullable();
$table->string('cv_file',350)->nullable();
$table->text('summary')->nullable();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
How do I alter the table through migration and add these:
$table->foreign('nationality_id')->references('id')->on('countries');
$table->foreign('country_id')->references('id')->on('countries');
$table->foreign('state_id')->references('id')->on('state_origins');
$table->foreign('city_id')->references('id')->on('cities');
Thanks
create another migration like to alter existing table
public function up()
{
Schema::table('profiles', function (Blueprint $table) {
$table->foreign('nationality_id')->references('id')->on('countries');
$table->foreign('country_id')->references('id')->on('countries');
$table->foreign('state_id')->references('id')->on('state_origins');
$table->foreign('city_id')->references('id')->on('cities');
});
}
public function down() {
Schema::table('profiles', function (Blueprint $table) {
$table->dropForeign('nationality_id');
$table->dropForeign('country_id');
$table->dropForeign('state_id');
$table->dropForeign('city_id');
});
}

primary key is not added as reference to foreign key in laravel 6

I want to add a foreign key to my schools table but the primary key of the provinces table is not added to the foreign key reference.
This is my Schools Table
public function up()
{
Schema::create('schools', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string("name");
$table->unsignedTinyInteger("province_id");
});
}
and Provinces Table
public function up()
{
Schema::create('provinces', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string("name",255);
});
}
and this is my Foreign key constraint
public function up()
{
Schema::table('schools', function (Blueprint $table) {
$table->foreign('province_id')->reference('id')->on('provinces');
});
}
and this is the error
enter image description here
If there is a solution tell me.
Thanks.
Try this and also check the sequence of your migrations.
public function up()
{
Schema::create('student_profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string("name",64);
$table->string("father_name",64);
$table->string("last_name",64);
$table->string("grand_father_name",64);
$table->string("graduation_year",4)->unique();
$table->enum("gender",['0','1']);
$table->unsignedSmallInteger('school_id')->nullable();
$table->unsignedTinyInteger("province_id")->nullable();
$table->foreign('school_id')->reference('id')->on('schools')-
>onDelete('set null');
$table->foreign('province_id')->reference('id')->on('provinces')->onDelete('set null');
});
}
public function up()
{
Schema::table('schools', function (Blueprint $table) {
$table->unsignedBigInteger('province_id')->nullable();
$table->foreign('province_id')->reference('id')->on('provinces')
->onDelete('set null');
});
}

General error: 3730 Cannot drop table 'questionnaires' referenced by a foreign key constraint (SQL: drop table if exists `questionnaires`) Laravel

I have a problem when I rollback my boards. It is as follows:
SQLSTATE[HY000]: General error: 3730 Cannot drop table 'questionnaires' referenced by a foreign key constraint 'questions_questionnaire_id_foreign' on table 'questions'. (SQL: drop table if exists `questionnaires`)
For this I have 2 tables involved, which is Questionnaire and Question.
Question
lass CreateQuestionsTable extends Migration{
public function up(){
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('questionnaire_id');
$table->text('description');
$table->text('iframe');
$table->text('image')->nullable();
$table->timestamps();
});
}
public function down(){
Schema::table('questions', function (Blueprint $table) {
$table->dropColumn('questionnaire_id');
$table->dropForeign('questions_questionnaire_id_foreign');
});
Schema::dropIfExists('questions');
}
}
Questionnaire
class CreateQuestionnairesTable extends Migration{
public function up(){
Schema::create('questionnaires', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->string('description');
$table->timestamps();
});
}
public function down(){
Schema::dropIfExists('questionnaires');
}
}
And then add the questionnaire FK to the question table. Alter table
class AddToQuestionnaireIdToQuestionsTable extends Migration{
public function up(){
Schema::table('questions', function (Blueprint $table) {
$table->foreign('questionnaire_id')->references('id')->on('questionnaires')
->onDelete('cascade')
->onUpdate('cascade');
});
}
public function down(){
Schema::dropIfExists('questions');
}
}
However when I rollback I get the aforementioned error. What am I doing wrong?
You are dropping the question table in the wrong place. You should rollback only what you did roll forward.
Question: if you created a table, here you drop the table.
Class CreateQuestionsTable extends Migration
{
public function up()
{
Schema::create('questions', function (Blueprint $table)
{
$table->id();
$table->unsignedBigInteger('questionnaire_id');
$table->text('description');
$table->text('iframe');
$table->text('image')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('questions');
}
}
ForeigKey: if you created a column and/or foreign key, drop then here.
class AddToQuestionnaireIdToQuestionsTable extends Migration
{
public function up()
{
Schema::table('questions', function (Blueprint $table)
{
$table->foreign('questionnaire_id')
->references('id')
->on('questionnaires')
->onDelete('cascade')
->onUpdate('cascade');
});
}
public function down()
{
Schema::table('questions', function (Blueprint $table)
{
$table->dropForeign('questions_questionnaire_id_foreign');
$table->dropColumn('questionnaire_id');
});
}
}
If you want to delete a table and get a foreign key error, do as the code below in SQL😂
set foreign_key_checks=0;
drop table `yourSchema`.`yourTable`;

Laravel 7 General error: 1215 Cannot add foreign key constraint

I've been researching this for hours, can't seem to solve it. Here is the error
General error: 1215 Cannot add foreign key constraint (SQL: alter table 'users' add constraint 'users_discord_id_foreign' foreign key ('discord_id') references 'discord_o_auths' ('id'))
Here is my DiscordOAuths Migration:
public function up()
{
Schema::create('discord_o_auths', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->integer('id')->unique();
$table->string('access_token')->unique();
$table->string('refresh_token')->unique();
$table->bigInteger('token_expiration');
$table->timestamps();
});
}
And here is my Users Migration.
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->id();
$table->boolean('admin')->default(false);
$table->integer('color_scheme')->default(0);
$table->rememberToken();
$table->timestamps();
});
Schema::table('users', function($table) {
$table->engine = "InnoDB";
$table->integer('discord_id')->unsigned();
$table->foreign('discord_id')->references('id')->on('discord_o_auths');
});
}
The DiscordOAuths table is created before the Users table as well. What am I doing wrong?
You're trying to assign a foreign key constraint to an integer column, which is not the same as the unsigned columns that Laravel uses for its id's.
In your DiscordOAuths you have to replace $table->integer('id')->unique(); with $table->bigIncrements('id'); or the new method added in Laravel 7 $table->id(); which is an alias of the previous one.
Your discord_id column in the users migration also needs to be an unsigned column. You have to define it using either $table->unsignedBigInteger('discord_id'); or its alias that came with Laravel 7: $table->foreignId('discord_id');
So your migrations would look like this:
For DiscordOAuths
public function up()
{
Schema::create('discord_o_auths', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->id();
$table->string('access_token')->unique();
$table->string('refresh_token')->unique();
$table->bigInteger('token_expiration');
$table->timestamps();
});
}
And for users it would be like this:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->id();
$table->boolean('admin')->default(false);
$table->integer('color_scheme')->default(0);
$table->rememberToken();
$table->timestamps();
});
Schema::table('users', function($table) {
$table->engine = "InnoDB";
$table->foreignId('discord_id');
$table->foreign('discord_id')->references('id')->on('discord_o_auths');
});
}

laravel migration use auto increment when its not primary

I'm trying to create a table with Laravel migrations but I'm having some trouble. I just need to create a table with a primary pair ('user_id' and 'media_id'), being 'inc' an auto increment. I can do it in MySQL, but I can't manage to do it with Laravel Migrations since increments() also set the field as primary. error i get
SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined as a key
thats i hae done so far
public function up()
{
Schema::create('tagtables', function (Blueprint $table) {
$table->integer('media_id');
$table->integer('user_id');
$table->boolean('approved')->default(false);
$table->increments('inc')->unsigned();
$table->timestamps();
$table->dropPrimary('tagtables_inc_primary');
$table->primary(array('user_id','media_id'));
// $table->foreign('media_id')->references('id')->on('media')->onUpdate('cascade')->onDelete('cascade');
// $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
});
// Schema::table('tagtables', function (Blueprint $table) {
// //$table->increments('id');
// $table->primary(array('user_id','media_id'));
// $table->foreign('media_id')->references('id')->on('media')->onUpdate('cascade')->onDelete('cascade');
// $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
// });
}
I think you need this:
public function up()
{
Schema::create('tagtables', function (Blueprint $table) {
$table->increments('inc');
$table->integer('media_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->boolean('approved')->default(false);
$table->timestamps();
$table->index(['user_id', 'media_id']);
$table->foreign('media_id')->references('id')->on('media')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
});
}
and put this in the model:
protected $primaryKey = 'inc';
I found solution to problem which is ti define that column inc (which auto increments) after creating schema.
That how it should be
public function up()
{
Schema::create('tagtables', function (Blueprint $table) {
$table->integer('media_id');
$table->integer('user_id');
$table->boolean('approved')->default(false);
// $table->increments('inc');
$table->timestamps();
// $table->dropPrimary( 'tagtables_inc_primary' );
$table->primary(array('user_id','media_id'));
// $table->foreign('media_id')->references('id')->on('media')->onUpdate('cascade')->onDelete('cascade');
// $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
});
DB::statement('ALTER Table tagtables add id INTEGER NOT NULL UNIQUE AUTO_INCREMENT;');
// Schema::table('tagtables', function (Blueprint $table) {
// //$table->increments('id');
// $table->primary(array('user_id','media_id'));
// $table->foreign('media_id')->references('id')->on('media')->onUpdate('cascade')->onDelete('cascade');
// $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
// });
}
chema

Resources