我正在尝试用参考数据向我的mySQL数据库播种。根据我的迁移功能,我遇到困难的特定表具有无效的外键,该键可将其映射到同一表以表示父母/子关系:
:public function up()
{
Schema::create('groups', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('parent_group_id')->unsigned()->nullable();
$table->foreign('parent_group_id')->references('id')->on('groups');
$table->string('value');
$table->softDeletes();
});
}
问题是试图将外键作为NULL在顶级行中播种。如果我不在任何插入的行上包含该字段,则种子可以按预期工作。当我仅将字段添加到孩子行中时,它会期望每行都有相同的字段数,并且错误为:
[PDOException]
SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column
count doesn't match value count at row 2
我找不到有关如何将值播种到null的任何参考。我进行的最后一次尝试是:
<?php
use IlluminateDatabaseSeeder;
class GroupsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('groups')->insert([
[
'parent_group_id' => [NULL],
'value' => 'Group1'
],
[
'parent_group_id' => 1,
'value' => 'Subgroup1'
],
[
'parent_group_id' => 2,
'value' => 'Subgroup2'
]
]);
}
}
错误地出现到Array to string conversion
。
使用'[NULL]'
错误到General error: 1366 Incorrect integer value
。我尝试了其他变体,但没有运气。在种子中插入零值的正确方法是什么?任何帮助都赞赏。问候,
您只能使用PHP null
值,Laravel足够聪明,可以将其转换为数据库的空值。
DB::table('groups')->insert([
[
'parent_group_id' => null,
'value' => 'Group1'
],
[
'parent_group_id' => 1,
'value' => 'Subgroup1'
],
[
'parent_group_id' => 2,
'value' => 'Subgroup2'
]
]);
使用[
和]
时,您会创建一个PHP数组,这就是为什么您会收到该错误。