SQLSTATE[HY000]: General error: 1005 during a migration in Laravel - laravel

I am using Laravel 6. I want to run my migration files but during the migration of my "create_users_table" file appears the following error:
SQLSTATE[HY000]: General error: 1005 Can't create tab
le `thenewmeetingapp`.`#sql-f3c_b8` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table
`users` add constraint `users_permission_id_foreign` foreign key (`permission_id`) references `permissions` (`id`))
I think the error is between the table "users" and the table "permissions" (every user must have a permission and every permission could have many users).
However the table "users" is related even with the table "meeting_user" that is a joined table with the table "meetings".
users:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('surname');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('username')->unique();
$table->string('password');
$table->bigInteger('permission_id')->unsigned();
$table->enum('is_active', array(0, 1))->default(1);
$table->rememberToken();
$table->timestamps();
$table->foreign('permission_id')->references('id')->on('permissions');
});
permissions:
Schema::create('permissions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
meeting_user:
Schema::create('meeting_user', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('meeting_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('meeting_id')->references('id')->on('meetings')->onDelete('cascade');
});
The migration of the users table is the first migration to be run. However I tried also to run before the migration of the permissions table and after the user's one but nothing changed. The error was the same.
Is someone able to help me?

You need to have the other table your foreign key on users points to, permissions, created before you can add the key to users. So this particular migration that creates the users table can NOT be first. The other table, permissions, has to exist before you can reference it.
If you can't reorder these migrations you can remove the foreign key part from the users migration. Then create a new migration that alters the users table and adds the foreign key; which would now (via timestamp) run after the permissions table migration.

As explained by #lagbox's answer, you cannot create a foreign key to a column in a table that does not yet exist.
So, the approach I propose is that you change the order of the migrations, changing the timestamp of the file name of each migration, so that they are executed in the following order:
permissions
users
meetings,
meeting_user
Note that after changing the file names, you must run composer dump-autoload before running the migrations again.

Related

how to solve this erorr SQLSTATE[HY000]: General error: 1005 Can't create table

I have this error when run migration
SQLSTATE[HY000]: General error: 1005 Can't create table tms-app.#sql-1e64_2b (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table projects add constraint projects_cout_id_foreign foreign key (cout_id) references couts (id) on update cascade)
this is projects table:
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('libelle');
$table->string('libelle_long');
$table->string('direction');
$table->integer('cout_id')->unsigned();
$table->foreign('cout_id')
->references('id')->on('couts')
->onUpdate('cascade');
$table->foreign('status')
->referenecs('id')->on('statuses')
->onUpdate('cascade')
->onDelete('cascade');
$table->timestamps();
});
Sometimes this error happens, when we define foreign key and you should use bigInteger('') or use unsignedBigInteger('').
Use the code below:
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('libelle');
$table->string('libelle_long');
$table->string('direction');
$table->bigInteger('cout_id')->unsigned();
$table->bigInteger('status')->unsigned();
$table->foreign('cout_id')->references('id')->on('couts')->onDelete('cascade');
$table->foreign('status')->references('id')->on('statuses')->onDelete('cascade');
$table->timestamps();
});
Note: In tables couts & statuses change the id field $table->increments('id'); to $table->bigIncrements('id');
This error should be casuses by the following miss-configuration below I mentioned, be sure all of them to be configured correctly
1: Laravel migration foriegn key should be assgined as bigInteger or unsignedBigInteger
example:
$table->unsignedBigInteger('user_id');
or
$table->bigInteger('user_id')->unsigned();
and for assigning foriegn key attribute you should do
$table->foriegn('user_id')->reference('id')->on('users'); // if you need further attribtute you can chain to this line
2: be sure that the order of migration file is formed correclty because Laravel will migrate table based on timestamp for example if need a foreign key from user table first you need to create user table then the child table the timestamp of users table should be older than child (even 1 second)

Laravel migration error in foresign key 150

I started working on small project using Laravel latest version, i try to make a foreign key between two table ( Buildings and Appartmens ) but i get an error message contain :
("SQLSTATE[HY000]: General error: 1005 Can't create table `project`.`apartments` (errno: 150 "Foreign key constraint is incorrectly formed")")
this is my buildings table schema :
Schema::create('buildings', function (Blueprint $table) {
$table->id();
$table->string('address');
$table->timestamps();
});
this is my apartments table schema :
Schema::create('apartments', function (Blueprint $table) {
$table->id();
$table->string('number');
$table->integer('monthly_price');
$table->integer('rooms');
$table->integer('bath_room');
$table->string('description');
// Foreign Key
$table->foreignId('building_id')->constrained('buildings');
// Record Times
$table->timestamps();
});
It looks like your apartments migration runs before your buildings migration, so no foreign key can be created because the buildings table has not yet been created.
To fix this you can change the date that prefixes the migration, for example:
2020_08_03_140214_create_apartments_table
2020_08_03_140387_create_buildings_table
to:
2020_08_03_140387_create_buildings_table
2020_08_03_140388_create_apartments_table
Don't forget to run a composer dump-autoload afterwards in order to update the class maps as well.

Issues with foreign constraints -

I tried to follow the documentation of laravel and laracasts, however I get an error in my migrations concerning foreign keys.
I have articles about games that are written by authors (users), so I want the user Id for the article.
This is my games table:
public function up()
{
Schema::create('games', function (Blueprint $table) {
$table->id('id');
$table->timestamps();
$table->string('name', 100);
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->text('description');
$table->string('publisher');
$table->string('url');
});
}
And this my user table:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
If I understand correct I name the column in the games table 'user_id', and it references to the Id of the user, which is called 'id' in the user table?
When migrating however i get the error theres no user_id.
SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'user_id' doesn't exist in table (SQL: alter table gamesadd constraintgames_user_id_foreign foreign key (user_id) references users (id) on delete cascade)
Can someone tell me what I am doing wrong? Am I mixing up where I should refer to 'id' in the user table?
Migrations by default are run with the same order that they are been created, and in your case, the games migration is been executed before the user migration, and so you when migrating the games migration, there is no user table, and so
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
Will fail.
In order to solve this problem, rename the user migration with a date before the one that has the games migration
Thanks to #lagbox for having pointed it out:
This line is not creating a new field, but is just adding a constrain
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
Instead you should first create the field and then create the constrain:
$table->bigInteger('user_id)->...;
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
The way I usually do it is :
Creating the migrations files (containing all the fields)
Creating alterations files (adding FK)
Like that, when I run php artisan migrate the order of the migrations doesn't block anything.
With your code above you are trying to add a foreign constraint on a field which doesn't exist yet

Why it appears the error "General error: 1005 Can't create table"?

I have these two migration files one to create a faq_channels table and another to create a faq_questions table. However, I'm not understanding why it is showing an error:
SQLSTATE[HY000]: General error: 1005 Can't create table `test`.`faq_questions` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `faq_questions` add const
raint `faq_questions_channel_id_foreign` foreign key (`channel_id`) references `faq_channels` (`id`) on delete cascade)
Do you know why?
// create_faq_channels_table
public function up()
{
Schema::create('faq_channels', function (Blueprint $table) {
$table->id();
$table->string('channel');
$table->text('description');
$table->timestamps();
});
}
// create_faq_questions_table
Schema::create('faq_questions', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('channel_id');
$table->string('question');
$table->text('response');
$table->timestamps();
$table->foreign('channel_id')->references('id')->on('faq_channels')->onDelete('cascade');
});
I have these two migration files one to create a faq_channels table
and another to create a faq_questions table.
Make sure that migration file for 'faq_channels' table runs before the migration file for 'faq_questions' table. Generally this type of error rises when the parent table is not created before declaring foreign key constraint.
Also edit your migration files according to Talha F.'s answer.

Laravel - unable to migrate DB

Im learning laravel, and now im unable to migrate the database. I have already created the db in phpmyadmin, have read the documentation and made a research on the net about the issue. However, when i make migrate, it keeps sending the same message:
SQLSTATE[HY000]: General error: 1005 Can't create table `YYYY`.`#sql-269c_1c1` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table ` cars` add constraint `cars_company_id_foreign` foreign key (`Company_id`) references `companies` (`id`) on delete cascade on update cascade)
This is the code:
2014_10_12_000000_create_cars_table
Schema::create('cars', function (Blueprint $table) {
$table->increments('id');
$table->integer('Company_id')->unsigned();
$table->foreign('Company_id')->references('id')->on('companies')->onDelete('cascade')->onUpdate('cascade');
$table->string('Model');
});
2014_10_12_000000_create_companies_table
Schema::create('companies', function (Blueprint $table) {
$table->increments('id');
$table->string('Company');
});
Laravel tries to run your migrations in order of 1) time, 2) alphabet. Since you gave both of your migrations the same time, it's going by alphabetical order instead.
What this means in practice is that you're trying to create the cars table first, with a foreign key constraint pointing to a table companies - but this table does not yet exist, since it's going to be created in the next migration.
Name your migrations properly and it should resolve itself. :)
Yea as Joel Said be careful on migration naming convention.
To avoid these errors you can use migration commands
step1
Run below from command line
php artisan make:migration create_companies_table
step2
This will make blank migration schema in your database and then edit it like below
Schema::create('companies', function (Blueprint $table) {
$table->increments('id');
$table->string('Company');
});
step 3
Run below from command line
php artisan make:migration create_companies_table
step 4
This will make blank migration schema in your database and then edit it like below
Schema::create('cars', function (Blueprint $table) {
$table->increments('id');
$table->integer('Company_id')->unsigned();
$table->foreign('Company_id')->references('id')->on('companies')->onDelete('cascade')->onUpdate('cascade');
$table->string('Model');
});

Resources