我需要製作一個帶有複合主鍵的表。我一直在尋找多個選項來解決這個問題,以創建一個AUTO_INCREMENT字段以及其他一些字段,並使它們成爲一個複合主鍵,但最終我成功地做到了這一點;帶複合主鍵的Laravel種子表
class CreateSpecificationTable extends Migration {
public function up()
{
Schema::create('specification', function(Blueprint $table){
$table->increments('specificationID');
$table->integer('categoryID', false, true);
$table->string('name', 100);
$table->dateTime('created_at');
$table->dateTime('updated_at')->nullable()->default(null);
$table->dateTime('deleted_at')->nullable()->default(null);
$table->foreign('categoryID')->references('categoryID')->on('categories');
});
DB::unprepared('ALTER TABLE specification DROP PRIMARY KEY, ADD PRIMARY KEY(specificationID, categoryID, name)');
}
此表的模式非常簡單:
class Specification extends Eloquent {
protected $table = 'specification';
protected $primaryKey = array('specificationID', 'categoryID', 'name');
}
然後播種機看起來是這樣的:
class SpecificationSeeder extends Seeder {
public function run()
{
Specification::create(array(
'categoryID'=>1,
'name'=>'size',
));
Specification::create(array(
'categoryID'=>2,
'name'=>'resolution',
));
Specification::create(array(
'categoryID'=>1,
'naam'=>'connection',
));
}
}
然而,當我運行從CMD的php artisan db:seed
命令,我出現以下錯誤:
[ErrorException]
PDO::lastInsertId() expects parameter 1 to be string, array given
奇怪的是,我已經內置了很多其他表在此應用程序已經這樣,但是這是第一個地方在模型中protected $primaryKey
組成的陣列與領域,而不是一個單一的主鍵。
而且,儘管給這個錯誤,第一個「種子」也得到添加到數據庫中,但後無來者。