Laravel:使用Faker为嵌套集合表设定种子
我正在使用Kalnoy/Nestedset,并试图使用faker为我的注释表设置种子,但出现“数组到字符串转换”错误 注释表如下所示:Laravel:使用Faker为嵌套集合表设定种子,laravel,nested-sets,faker,Laravel,Nested Sets,Faker,我正在使用Kalnoy/Nestedset,并试图使用faker为我的注释表设置种子,但出现“数组到字符串转换”错误 注释表如下所示: Schema::create('comments', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('user_id'); $table->unsignedIn
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
]),
],
],
],
],
]);
}
}
我还想确保子项的post id与父项的相同,但现在它返回null。create方法中数组的键应该是模型上存在的属性。在您的情况下,
children
不是Comment
模型上的属性
使用文档中的示例,您可以创建每个注释,然后在新模型上使用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
]));
});
});
根据我的经验,“数组到字符串的转换”通常是在工厂里进行的,通常是在冒牌货中进行的。某些facker helper方法使用第二个参数来指定数组或字符串。但我原以为,
段落
本来就可以了。看不到任何明显的错误。它成功了,谢谢!我将这段代码包装在“factory('App\Models\Post'::class,5)->create()->each(function($Post){)”中,以正确获取Post id,并运行Post seeder。