我需要制作一个带有复合主键的表。我一直在寻找多个选项来解决这个问题,以创建一个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
组成的阵列与领域,而不是一个单一的主键。
而且,尽管给这个错误,第一个“种子”也得到添加到数据库中,但后无来者。