我需要使用外鍵爲我的數據庫,但我不能這樣做,在命令行中運行遷移命令後,我得到這個錯誤:如何使用外鍵laravel 5.1遷移
[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 Cannot add foreign key constraint
樣品遷移:
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();
});
我嘗試與樣品新的遷移,但unsucce ssful:
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,但不成功再
我說的做,但unsuccessfull –
首先執行的供應商遷移,然後品嚐migration.Cause沒有供應商遷移supplier_id將不能作爲外鍵 –