简体   繁体   中英

SQLSTATE[HY000]: General error: 1005 Can't create table `business`.`users` (errno: 150 "Foreign key constraint is incorrectly formed") Laravel 7

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!

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM