当使用laravel迁移时尝试生成外键时
比如这个例子:
用户表
public function up()
{
Schema::create('flights', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->TinyInteger('color_id')->unsigned();
$table->foreign('color_id')->references('id')->on('colors');
$table->timestamps();
});
}
颜色表
public function up()
{
Schema::create('flights', function (Blueprint $table) {
$table->increments('id');
$table->string('color');
$table->timestamps();
});
}
有时物业不起作用
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
发生此错误的原因是[用户表]中的外键(类型)不同于[颜色表]中的主键(类型)
若要解决此问题,应更改[颜色表]中的主键
$table->tinyIncrements('id');
使用主键时
$table->Increments('id');
你应该用
Integer
作为外键
$table-> unsignedInteger('fk_id');
$table->foreign('fk_id')->references('id')->on('table_name');
使用主键时
$表->tinyincrements('id');
你应该用
unsignedTinyInteger
作为外键
$table-> unsignedTinyInteger('fk_id');
$table->foreign('fk_id')->references('id')->on('table_name');
使用主键时
$table->smallIncrements('id');
你应该用
unsignedSmallInteger
作为外键
$table-> unsignedSmallInteger('fk_id');
$table->foreign('fk_id')->references('id')->on('table_name');
使用主键时
$table->mediumIncrements('id');
你应该用
unsignedMediumInteger
作为外键
$table-> unsignedMediumInteger('fk_id');
$table->foreign('fk_id')->references('id')->on('table_name');