Laravel migration won't reference second foreign key - laravel

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.

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: adding foreign key to the same table where ID is a string

I'm trying to make "categories" migration, where each category refers it's parent category by ID in the same table.
Migration:
Schema::create('categories', function (Blueprint $table) {
$table->string('id', 36)->primary();
$table->string('parent_id', 36)->nullable();
$table->foreign('parent_id')->references('id')->on('categories');
$table->string('name');
});
But i'm getting next error:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table categories add constraint categories_parent_id_foreign foreign key (parent_id) references categories (id))
Field types are the same, and I don't know, what to do.
Removing "->nullable()" has no effect.
Laravel Framework version 6.20.7
Thanks.
Add the foreign key constraint in another run like as below
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->string('id', 36)->primary();
$table->string('parent_id', 36)->nullable();
$table->string('name');
});
Schema::table('categories',function (Blueprint $table){
$table->foreign('parent_id')->references('id')->on('categories');
});
}

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');

Foreign key is incorectly formed in 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.

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint Laravel 5.8

I am trying to make a foreign key to "users" table using Laravel 5.8.
Laravel 5.8 auto generated migration table is as follows,
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();
});
}
Then from my "repositories" table I am referencing "users" table as follows,
Schema::create('repositories', function (Blueprint $table) {
$table->string('id', 8)->primary();
$table->string('name')->nullable(false);
$table->string('size')->nullable(false);
$table->unsignedInteger('user_id')->nullable(false);
$table->timestamps();
});
Schema::table('repositories', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users');
});
But I am getting "General error: 1215 Cannot add foreign key constraint" error on this code. There were many solutions related to this problem.
General error: 1215 Cannot add foreign key constraint in laravel
Migration: Cannot add foreign key constraint in laravel
Laravel migration "Cannot add foreign key constraint" error with MySQL database
I tried the above solutions already. But my problem was not solved
Try this
Schema::create('repositories', function (Blueprint $table) {
$table->string('id', 8)->primary();
$table->string('name')->nullable(false);
$table->string('size')->nullable(false);
$table->unsignedBigInteger('user_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
According to laravel 5.8 Foreign Key Constraints
Schema::table('posts', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
Starting with Laravel 5.8, bigIncrements is used instead of increments for primary keys. If you are using bigIncrements for your primary key you must declare the user_id field as bigInteger instead of integer. In this way the field of the primary key and the foreign key will share the same type of data, otherwise you will get an error
Its probably because the user_id column does not match the id column.
user_id needs to be of type bigInteger and also be indexed.
Ref: Setting a foreign key bigInteger to bigIncrements in Laravel 5.4

Resources