0
votes

I need to create a one to many relationship between users (created from laravel 7 auth scaffolding) and categories. But when I run migration I get this error: Migrating: 2014_10_12_000000_create_users_table

Illuminate\Database\QueryException

SQLSTATE[HY000]: General error: 1005 Can't create table business.users (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table users add constraint users_category_id_foreign foreign key (category_id) references catgories (id) on delete cascade)

here is the users schema:

Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('category_id');
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();

        $table->foreign('category_id')->references('id')->on('catgories')
        ->onDelete('cascade');

    });

And this the on of categories:

Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('category');
        $table->timestamps();
    });

I have done some searches and I found out that there are two reasons for such an error, the first is that the categories table migration should be done before the users table one, and the second is that the category id datatype on the users schema and the one of the id on the category must be the same, I verified both of tese conditions and I am still getting the same error. I would be so grateful if someone can tell me what's wrong!

2
How did you made categories migration go first ? can you add the migration name for categories ?N69S
I did the migration through this command: php artisan migrate --path=/database/migrations/2020_08_22_121822_create_categories_table.php and then, I did the users migration through: php artisan migrate --path=/database/migrations/2014_10_12_000000_create_users_table.phpHamou Ait Abderrahim
you dont have to do it manualy, laravel migrate using the date as the order (actualy just the name but it starts with the date) just change the users migration to 2020_08_22_121823_create_users_table.php and it will migrate in the correct orderN69S
also as @Sobir pointed out, you have a mistype on('catgories')N69S
Very useful information, especially in my project case, thank you!Hamou Ait Abderrahim

2 Answers

1
votes

Change on('categories') instead of on('catgories') You wrote catgories. But it must be categories

$table->foreign('category_id')->references('id')->on('categories')
        ->onDelete('cascade');
0
votes

That happens when the types of the Foreign key are not matching the type of the primary key.

Make sure that category_id is the exact same type and length then the primary key of the category table categories. So if you declared as an unsigned big integer, make sure categories.id is an unsigned big integer.