【发布时间】:2014-07-31 20:50:53
【问题描述】:
我需要用复合主键创建一个表。我一直在寻找多种选项来解决问题,以创建一个 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');
}
然后播种机是这样的:
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 由一个包含字段的数组组成,而不是一个单独的首要的关键。
此外,尽管出现此错误,但第一个“种子”确实会添加到数据库中,但之后就没有了。
【问题讨论】: