我需要制作一个含有复合主键的表格。我一直在寻找多种解决方案,通过创建一个AUTO_INCREMENT字段以及其它一些字段,并将它们组成一个复合主键来解决这个问题,但最终我是通过以下方式成功实现的:
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');
}
然后 Seeder 的样式如下:
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
由字段数组组成而不是单个主键的表格。此外,尽管出现了此错误,但第一个“种子”确实已被添加到数据库中,但之后没有更多的添加。