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');
});
Related
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.
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.
Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails
users Table
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();
});
cv table
Schema::create('cvs', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('name')->nullable();
$table->string('contact')->nullable();
$table->string('contact2')->nullable();
$table->string('gender')->nullable();
$table->string('email')->unique()->nullable();
$table->string('paddress')->nullable();
});
Reason can be:
your migration of CSV is before Users.
Take a look migration names (and dates). It should be:
2019_02_01_101010_create_users_table.php
2019_02_02_101010_create_csv_table.php (look, date is 2019_02_02)
Then fire php artisan:migrate
Be sure that in other migrations you have proper dates. Migration can not work if one table want relation with table that was not created yet.
Good luck!
In this situation you need to migrate the users table first, then the cvs
to do that:
php artisan migrate --path=/database/migrations/selected
if you have run migration before you need to migrate
php artisan migrate --path=/database/migrations/2014_10_12_000000_create_users_table.php
then run
php artisan migrate
It'll automatically migrate all the rest of the tables for you
Hope this helps
A project I am working on uses a mysql db for both testing & development (different db). When running php artisan migrate:refresh everything works fine.
However, when running tests it fails to run all migrations with the following error:
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1005 Can't create table `cmstatic_test`.`#sql-5008_121` (errno: 121 "Duplicate key on write or update") (SQL: alter table `project_user` add constraint `project_user_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)
Here is my migration up method
public function up()
{
Schema::create('project_user', function (Blueprint $table) {
$table->unsignedBigInteger('project_id');
$table->foreign('project_id')
->references('id')->on('projects')
->onDelete('cascade');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
$table->unsignedBigInteger('role_id');
$table->foreign('role_id')
->references('id')->on('roles');
$table->timestamps();
});
}
I don't get how there can be a duplicate key set for this table.
My tests look like
use Illuminate\Foundation\Testing\RefreshDatabase;
class AuthTest extends TestCase
{
use RefreshDatabase;
...
Update:
if I remove
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
The tests can be run again. However, I want that foreign key relation -.-
Update2:
I checked the table structure after removing the line that adds the foreign key and obviously the foreign key is not set. So no other migration is doing the same.
In my case I had 2 tables
page_translations
pr_page_translations
I had all sympthoms described in 1st post. I don't believe there can be an "error" in DB. So I searched and found the cause.
There was a foreign key named "page_translations_page_id_foreign" in table #1. When I was trying to add FK with same name to tabe #2 I got my "duplicate" error. So I added "pr_" prefix to FK name in table #2 "pr_page_translations_page_id_foreign".
Another solution that also worked for me was to rename already existing FK in table #1.
Conclusion: FK names across all tables must be unique.
After this I searched for explanation, and here it is: Why do MySQL foreign key constraint names have to be unique?
Try this:
public function up()
{
if (!Schema::hasTable('project_user')) {
Schema::create('project_user', function (Blueprint $table) {
$table->unsignedBigInteger('project_id');
$table->foreign('project_id')
->references('id')->on('projects')
->onDelete('cascade');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
$table->unsignedBigInteger('role_id');
$table->foreign('role_id')
->references('id')->on('roles');
$table->timestamps();
});
}
}
It seems like there was an error with my database itself. I've deleleted the tables multiple times and tried it again and the error was still there.
However, deleting the whole database and re-creating it solved the
issue.
This might be interesting for anyone facing this issue aswell.
I am trying to learn one-to-one relations. I am using Laravel 5.5.13.
My simple app is this:
I create a App\Message. I optionally can associate a App\Task with it.
My goal:
Once a App\Task is associated, if the task is deleted, it should cascade delete the App\Message row.
And the reverse, if the App\Message is deleted, it should cascade and delete the App\Task row.
However I am having an error on migrate because the tasks_table is created AFTER the messages_table.
Here is my migration:
2017_10_15_021803_create_messages_table.php:
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->integer('task_id')->unsigned()->nullable();
$table->text('body');
$table->timestamps();
$table->foreign('task_id')->references('id')->on('tasks')->onDelete('cascade'); //// IF I COMMENT THIS OUT THE MIGRATION WORKS, BUT I NEED THIS IN
});
}
And for App\Task 2017_10_15_023343_create_tasks_table.php:
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
$table->integer('message_id')->unsigned();
$table->timestamps();
$table->foreign('message_id')->references('id')->on('messages')->onDelete('cascade');
});
}
If I comment out the $table->foreign('task_id')->references('id')->on('tasks')->onDelete('cascade'); then the migration works, BUT i need the deletion of the message when the task is deleted, and without this line that won't happen.
The error I get after running php artisan migrate is:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table petfolk.#sql-42e8_16f (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table messages add constraint messages_task_id_foreign foreign key (task_id) references tasks (id) on delete set null)
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table petfolk.#sql-42e8_16f (errno: 150 "Foreign key constraint is incorrectly formed")
Just create third migration and move foreign key adding logic in the migration:
Schema::table('messages', function (Blueprint $table) {
$table->foreign('task_id')->references('id')->on('tasks')->onDelete('cascade');
}
It will work when both tables will be created.
A one-to-one relationship links one row in a database table to one (and only one) row in another table.
onDelete('cascade') is used when there is an intermediate, also known as a pivot, table between two tables in a many-to-many relationship. You do not need this for a one-to-one relationship because the link to the messages table only exists in the row of the tasks table (and that is being deleted).
Try this for the tasks table migration:
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
$table->integer('message_id')->unsigned()->nullable();
$table->foreign('message_id')->references('id')->on('messages');
$table->timestamps();
});
}