所以我正在尝试在 laravel 的迁移文件中设置一个外键,因此用户表很简单,但我尝试使用 bigIncrements 而不是站立增量。
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->bigIncrements('id')->unsigned();
$table->string('user_id')->unique();
$table->string('avatar');
$table->string('name');
$table->string('email')->unique();
$table->string('password')->nullable();
$table->rememberToken();
$table->timestampsTz();
});
}
当我做另一个表时,我尝试向其添加外键,我收到一个错误,指出外键格式不正确。我对如何感到困惑,因为我正在匹配列类型。这是另一张表。
public function up()
{
Schema::create('social_logins', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->unsigned()->index();
$table->string('provider', 32);
$table->string('provider_id');
$table->string('token')->nullable();
$table->string('avatar')->nullable();
$table->timestamps();
});
}
从以下位置删除unsigned()
:
$table->bigIncrements('id')->unsigned();
另一个迁移应如下所示:
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
....
$table->index('user_id');
原因是主要引用和外部引用必须属于同一类型。
bigIncrements()
想要unsignedBigInteger()
increments()
想要unsignedInteger()
如果您正在使用
$table->bigIncrements('id');
作为用户表中的主键:
然后使用
$table->unsignedBigInteger('user_id'); as foreign key
如果您使用$table->increments('id');
作为用户表中的主键,请使用
$table->unsignedInteger('user_id'); as freign key.
$table->increments(); creates just integer and $table->bigIncrements(); creates big integer.
因此,引用类型必须相同。
阅读更多 https://laravel.com/docs/4.2/schema#adding-columns
问题是bigIncrements
返回一个 unsignedBigInteger。 为了工作,外键必须是带有index()
的无符号大整数。