Laravel:用 Faker 播种嵌套集合 table

Laravel: seeding a nested set table with Faker

我正在使用 Kalnoy/Nestedset 并尝试使用 faker 播种我的评论 table,但是出现 "Array to string conversion" 错误。

评论 table 如下所示:

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
                            ]), 
                        ],
                    ],
                ],
            ],
        ]);
    }

}

我还想确保 children 的 post id 与 parent 的相同,但现在 returns 为空。

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
                    ]));
                });
            });