Ezatullah Tabish
Ezatullah Tabish

Reputation: 33

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

        });

Upvotes: 0

Views: 411

Answers (2)

Hedayatullah Sarwary
Hedayatullah Sarwary

Reputation: 2834

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

Upvotes: 2

MANSOOR KOCHY
MANSOOR KOCHY

Reputation: 374

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)

Upvotes: 0

Related Questions