我正在使用Kalnoy / Nestedset,并尝试使用fakerr为我的评论表添加种子,但是出现“数组到字符串转换”错误。
评论表如下:
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->unsignedInteger('post_id');
$table->text('body');
$table->timestamps();
$table->nestedSet();
});
评论工厂:
use Faker\Generator as Faker;
$factory->define(
App\Models\Comment::class,
function (Faker $faker) {
return [
'user_id' => function () {
return factory('App\Models\User')->create()->id;
},
'post_id' => function () {
return factory('App\Models\Post')->create()->id;
},
'body' => $faker->paragraph,
];
}
);
我真的无法弄清楚播种机的外观。这是我的尝试:
public function run(Post $post)
{
$node = factory('App\Models\Comment'::class, 3)->create([
'children' => [
[
factory('App\Models\Comment'::class, 2)->create([
'post_id' => $post->id
]),
'children' => [
[ factory('App\Models\Comment'::class, 1)->create([
'post_id' => $post->id
]),
],
],
],
],
]);
}
}
我还想确保子代的帖子ID与父代的ID相同,但现在它返回null。
答案 0 :(得分:2)
create
方法中数组的键应为模型上存在的属性。就您而言,children
不是Comment
模型上的属性。
使用Using Factories文档中的示例,您宁愿创建每个注释,然后在新模型上使用children()
关系来创建其子级。例如:
public function run(Post $post)
{
$node = factory('App\Models\Comment'::class, 3) // Create the root comments.
->create()
->each(function ($comment) use ($post) { // Add children to every root.
$comment->children()->saveMany(factory(App\Comment::class, 2)->make([
'post_id' => $post->id
]))
->each(function ($comment) use ($post) { // Add children to every child of every root.
$comment->children()->saveMany(factory(App\Comment::class, 2)->make([
'post_id' => $post->id
]));
});
});