Laravel: use primary index as foreign key?

2019-08-17 04:41发布

问题:

I have a hasOne relation between the model user and the model profilePresi. This means each user has either 0 or 1 president settings. Thus, the primary index of the profilePresi table is identical to the foreign key.

This is how I wanted to add the foreign key:

Schema::create('profilePresi', function (Blueprint $table) {
          $table->integer('idMember');
          $table->primary('idMember');
          $table->string('idCountry',2);
          $table->timestamps();
});

Schema::table('profilePresi', function($table) {
          $table->foreign('idMember')
                ->references('id')->on('users')
                ->onDelete('cascade');
});

However I get the following error:

How can I fix it? I am using InnoDB engine so I know that I am allowed to set index key as foreign key.

回答1:

Your users.id column is likely an unsigned integer, but your profilePresi.idMember is just an integer. To use as a foreign key, they both need to be either unsigned or not. Check if that's the case, and if so, just make the profilePresi.idMember unsigned as well - that should do it. :)



回答2:

Instead of using

$table->integer('idMember');

use

table->unsignedInteger('idMember');