我需要在我的数据库中使用外键,但是在命令行中运行迁移命令后,我无法这样做,我得到了以下错误:
[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL:alter table
samples
add constraint s amples_supplier_id_foreign foreign key (supplier_id
) referencessuppliers
(id
))[PDOException] SQLSTATE[HY000]: General error: 1215 无法添加外键约束
Samples 迁移:
Schema::create('samples', function (Blueprint $table) {
$table->Increments('id',true);
$table->string('variety',50);
$table->integer('supplier_id')->unsigned();
$table->foreign('supplier_id')->references('id')->on('suppliers');
$table->string('lot_number');
$table->date('date');
$table->integer('amount');
$table->integer('unit_id')->unsigned();
$table->foreign('unit_id')->references('id')->on('unit');
$table->string('technical_fact');
$table->string('comments');
$table->string('file_address');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('category');
$table->timestamps();
});
供应商迁移:
Schema::create('suppliers', function (Blueprint $table) {
$table->Increments('id',true);
$table->string('supplier',50);
$table->timestamps();
});
我尝试使用新的 migration 进行样例操作,但是不成功:
Schema::create('samples', function (Blueprint $table) {
$table->Increments('id',true);
$table->string('variety',50);
$table->integer('supplier_id')->unsigned();
$table->string('lot_number');
$table->date('date');
$table->integer('amount');
$table->integer('unit_id')->unsigned();
$table->string('technical_fact');
$table->string('comments');
$table->string('file_address');
$table->integer('category_id')->unsigned();
$table->timestamps();
});
Schema::table('samples', function($table) {
$table->foreign('supplier_id')->references('id')->on('suppliers');
$table->foreign('unit_id')->references('id')->on('unit');
$table->foreign('category_id')->references('id')->on('category');
});
我试图将主键的长度固定为10,但再次失败了。