Foreign key is incorectly formed in Laravel - laravel

I have the following two migration files:
Schema::create('words', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('book_id')->unsigned()->nullable();
$table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
$table->string('title');
$table->longText('definition', 2056);
$table->timestamps();
});
and:
Schema::create('books', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('word_id')->unsigned()->nullable();
$table->foreign('word_id')->references('book_id')->on('words');
$table->string('title');
$table->string('author')->nullable();
$table->date('start_date')->nullable();
$table->date('end_date')->nullable();
$table->integer('no_pages')->nullable();
$table->integer('current_page')->nullable();
$table->integer('status')->nullable();
$table->timestamps();
});
When I run the migrate command, the following error occur:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Ca
n't create table `words`.`#sql-16bc_76` (errno: 150 "Foreign key constraint is i
ncorrectly formed") (SQL: alter table `books` add constraint `books_word_id_fore
ign` foreign key (`word_id`) references `words` (`book_id`))
Why is this happens? I've added word_id into books table so I can count the words added for that book.

The problem could be that the tables that contain the id that is being used as a foreign id needs to be created before another table can reference it. Basically, you are creating a table and telling MySQL to reference another table's primary key but that table doesn't exist yet. Try to create them separately.

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 : Errcode: 150 "Foreign key constraint is incorrectly formed"

I am trying to execute this migration :
Users :
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->string('avatar_url');
$table->string('email_verified_at')->nullable();
$table->string('password')->unique();
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
Articles :
Schema::create('articles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->text('title');
$table->longText('body');
$table->enum('state', ['draft', 'published']);
$table->bigInteger('user_id')->unsigned();
$table->timestamps();
$table->softDeletes();
$table->foreign('user_id')
->references('id')->on('users')
->onUpdate('cascade')->onDelete('cascade');
});
But when I migrate I get the following error :
SQLSTATE[HY000]: General error: 1005 Can't create table blog_api.#sql-2b70_7b (Errcode: 150 "Foreign key constraint is inc
orrectly formed") (SQL: alter table articles add constraint articles_user_id_foreign foreign key (user_id) references users
(id) on delete cascade on update cascade)
I already tried to rename big integer and big increments to simple integer and increments withouth success.
There should be one unassignedBigInteger and then you set your foreign key.
https://laravel.com/docs/5.8/migrations#foreign-key-constraints Please check the official documentation
Besides,
Please be carefull with order of migration. It starts from the first file through to latest one, so if you are trying to set foreign key for the table hasn't been created yet, it will throw an error.
E.g
Users table has foreign key relation with articles and like following;
create_users_table
create_articles_table
Since articles table not created yet, you will not be able to assign. For such cases like this, i suggest you to use "add_foreign_keys_to_articles" after all basic structure of tables created.
Schema::table('articles', function(Blueprint $table)
{
$table->foreign('user_id')
->references('id')->on('users')
->onUpdate('cascade')->onDelete('cascade');
});

Foreign Key makes Problems in Laravel 5.6

I would like to program an inventory system and need 3 tables for it. These can also be generated via artisan without a foreign key. But as soon as I want to add a foreign key, I get the following error message.
SQLSTATE[HY000]: General error: 1005 Can't create table `inventar`.`#sql-fd4_141` (errno: 150 "Foreign key constraint is incorrectly formed")
(SQL: alter table items add constraint items_lend_foreign foreign key (lend) references lending (id))
Here my Code:
Item Table
Schema::create('items', function (Blueprint $table) {
$table->string('barcode');
$table->primary('barcode');
$table->string('name');
$table->string('description')->nullable();
$table->string('room')->nullable();
$table->string('status')->nullable();
$table->string('annotation')->nullable();
$table->string('image')->nullable();
$table->integer('lend')->unsigned()->nullable();
$table->string('manufactor')->nullable();
$table->timestamps();
});
Schema::table('items',function ($table){
$table->foreign('lend')->references('id')->on('lending');
});
Lending Table
Schema::create('lending', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('personid')->unsigned();
$table->dateTime('startdate');
$table->dateTime('enddate');
$table->timestamps();
});
Schema::table('lending',function ($table){
$table->foreign('barcode')->references('barcode')->on('items');
$table->foreign('personid')->references('personid')->on('persons');
});
Persons-Table
Schema::create('persons', function (Blueprint $table) {
$table->integer('personid')->unsignd()->primary();
$table->string('firstname');
$table->string('lastname');
$table->string('email');
$table->string('annotation')->nullable();
$table->timestamps();
});
I've also googled, but found no solution that works for me.
Is it a problem that my primary key is a string?
Your problem comes in the line
Schema::create('persons', function (Blueprint $table) {
$table->integer('personid')->unsignd()->primary();
}
Change it to unsigned() from unsignd() and it will work fine.

errno: 150 "Foreign key constraint is incorrectly formed Laravel

Article migration
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('people_id');
$table->string('title');
$table->timestamps();
$table->foreign('author_id')->references('id')->on('people');
});
People Migration
Schema::create('people', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('twitter');
$table->timestamps();
});
Error
SQLSTATE[HY000]: General error: 1005 Can't create table `article`.`#sql-1204_c` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tab
le `articles` add constraint `articles_author_id_foreign` foreign key (`author_id`) references `people` (`id`))
i dont know what im doing wrong, both entity is consistent for me, i do not know why im receiving error 150
First make your people_id unsigned by-
$table->integer('people_id')->unsigned();
Change this line-
$table->foreign('author_id')->references('id')->on('people');
To this-
$table->foreign('people_id')->references('id')->on('people');
Check the order of your migrations. Run the people table migration first then articles table migration.
It's because you have not defined the author_id field
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('author_id');
$table->string('title');
$table->timestamps();
$table->foreign('author_id')->references('id')->on('people');
});

General error: 1005 Can't create table ,Foreign key constraint is incorrectly formed in laravel

why laravel schema reply
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table test.#sql-13cc_d0 (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table cities add constrai
nt cities_provinces_id_foreign foreign key (provinces_id) references provinces (id) on delete cascade)
[PDOException] SQLSTATE[HY000]: General error: 1005 Can't create
table test.#sql-13cc_d0 (errno: 150 "Foreign key constraint is
incorrectly formed")
first table
Schema::create('provinces', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->boolean('is_enable');
$table->boolean('is_deletable');
$table->boolean('is_editable');
$table->boolean('deleted');
$table->timestamps();
});
second table
Schema::create('cities', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('province_id')->unsigned()->index();
$table->boolean('is_enable');
$table->boolean('is_deletable');
$table->boolean('is_editable');
$table->boolean('deleted');
$table->timestamps();
$table->foreign('province_id')
->references('id')->on('provinces')
->onDelete('cascade');
});
You should make sure, your provinces table migration is running before cities table migration.
You should change provinces or cities migration file name to make sure timestamp at the beginning of provinces table migration file will be before cities table.
The time go ahead but i will comment something else.
Andile is right! You must have the same type. In this case, the foreign key should have the type bigInteger because you have bigIncrements on the reference table.
I think thats the solution for a little and boring debug. (sorry for my english)
Try to create table first and then add constraint:
Schema::create('cities', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('province_id')->unsigned()->index();
$table->boolean('is_enable');
$table->boolean('is_deletable');
$table->boolean('is_editable');
$table->boolean('deleted');
$table->timestamps();
});
Schema::table('cities', function (Blueprint $table) {
$table->foreign('province_id')->references('id')->on('provinces')->onDelete('cascade');
});
The foreign key and referencing table must be same type, the auto generated id are of bigInteger, so instead of defining your column as Integer use bigInteger insteated. That Solved the problem for me

Resources