Problems with table linkage in the Standard

Asked

Viewed 387 times

0

When I type php artisan migrate it generates this error:

  Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1005 
  Can't create table `blog`.`produtos` (errno: 150 "Foreign key constraint 
  is incorrectly formed") (SQL: alter table `produtos` add constraint 
  `produtos_user_id_foreign` foreign key (`user_id`) references `users` 
  (`id`) on delete cascade)


  Exception trace:

 PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table 
 `blog`.`produtos` (errno: 150 "Foreign key constraint is incorrectly 

Look at my code

Schema::create('produtos', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedInteger('user_id');
        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');

        $table->string('nome');
        $table->integer('quantidade');
        $table->integer('valor');
        $table->timestamps();
    });

Where I must be going wrong?

1 answer

1


The foreign key data format must be equal to the external value (primary key) which is related.

It is common for the user table primary key (blog.users.id) to be created using the method bigIncrements. That way, your column user_id of the products table should be created with the method unsignedBigInteger.

This way, both columns you are relating will be of format biginteger(20) unsigned

Browser other questions tagged

You are not signed in. Login or sign up in order to post.