简体   繁体   中英

Laravel: use primary index as foreign key?

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.

Instead of using

$table->integer('idMember');

use

table->unsignedInteger('idMember');

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

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