Laravel: use primary index as foreign key?

2019-08-17 05:02发布

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:

enter image description here

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

2条回答
该账号已被封号
2楼-- · 2019-08-17 05:13

Instead of using

$table->integer('idMember');

use

table->unsignedInteger('idMember');

查看更多
做自己的国王
3楼-- · 2019-08-17 05:19

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. :)

查看更多
登录 后发表回答