use*_*946 6 php pdo laravel laravel-4
我需要使用复合主键创建一个表.我一直在寻找解决问题的多个选项来创建一个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)');
}
Run Code Online (Sandbox Code Playgroud)
该表的模型非常简单:
class Specification extends Eloquent {
protected $table = 'specification';
protected $primaryKey = array('specificationID', 'categoryID', 'name');
}
Run Code Online (Sandbox Code Playgroud)
然后播种机看起来像这样:
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',
));
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我php artisan db:seed从CMD 运行命令时,我收到以下错误:
[ErrorException]
PDO::lastInsertId() expects parameter 1 to be string, array given
Run Code Online (Sandbox Code Playgroud)
奇怪的是,我已经用这种方式在这个应用程序中构建了很多其他表,但这是第一个在protected $primaryKey模型中由带有字段的数组组成的表,而不是只有一个主键.
此外,尽管给出了这个错误,第一个"种子"确实会添加到数据库中,但之后没有.
Eloquent 不支持复合键。您可以使用以下两种方法之一来完成此操作:
1) 使用 Seeder 的架构生成器并保持迁移不变。
class SpecificationSeeder extends Seeder {
public function run()
{
$data = array(
array(
'categoryID'=>1,
'name'=>'size',
),
array(
'categoryID'=>1,
'name'=>'size',
),
array(
'categoryID'=>1,
'naam'=>'connection',
)
);
DB::table('specification')->insert($data);
}
}
Run Code Online (Sandbox Code Playgroud)
2) 更改您的迁移,添加主键并定义唯一键。保持播种机原样
class CreateSpecificationTable extends Migration {
public function up()
{
Schema::create('specification', function(Blueprint $table){
$table->increments('id');
$table->integer('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->unique( array('specificationID', 'categoryID', 'name') );
$table->foreign('categoryID')->references('categoryID')->on('categories');
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4165 次 |
| 最近记录: |