与Laravel faker的嵌套关系 - laravel播种机

时间:2017-12-12 14:49:06

标签: php laravel factories eloquent--relationship

我想在laravel文档https://laravel.com/docs/5.5/database-testing

的关系部分中提到用户和评论的帖子播种机
  $users = factory(App\User::class, 3)
     ->create()
     ->each(function ($u) {
          $u->posts()->save(factory(App\Post::class)
            ->create()
            ->each(function($p){
                $p->comments()->save(factory(App\Comment::class,5)
                  ->create()
                  ->each(function($c){
                      $c->user()->save(factory(App\User::class)
                        ->make()
                      );
                  })
                );
              })
            );
        }
    );

预期产出是有3个用户发帖,每个帖子有5条评论。

但是发生了错误:

  

在Builder.php第2459行:调用未定义的方法   照亮\数据库\查询\生成器::保存()

3 个答案:

答案 0 :(得分:0)

试试这个:

$users = factory(App\User::class, 3)
     ->create()
     ->each(function ($u) {
          $u->posts()->save(factory(App\Post::class)->make())
            ->each(function($p){
                $p->comments()->save(factory(App\Comment::class,5)->make())
                  ->each(function($c){
                      $c->user()->save(factory(App\User::class)
                        ->make()
                      );
                  })
                );
              })
            );
        }
    );

常规foreach的解决方案

$users = factory(App\User::class, 3)->create();

foreach($users as $user){
    $post = $user->posts()
                          ->create(factory(App\Post::class)->make()->toArray());
    $post->comments()
                     ->createMany(
                               factory(App\Comment::class, 5)
                      ->make(['user_id' => factory(App\User::class)
                               ->create()->id])->toArray());
}

答案 1 :(得分:0)

例如,您的解决方案中有几个问题

$p->comments()->save(factory(App\Comment::class,5)

您正尝试使用save()保存多个注释,这将导致错误,您应改用saveMany()。 但是,解决问题的方法可能是:

$users = factory(App\User::class, 3)->create()
        ->each(function ($user) {
            $user->posts()->saveMany(factory(App\Post::class, 5)->make());
        });
foreach ($users as $user){
  foreach ($user->posts as $post){
    $post->comments()->saveMany(factory(App\Comment::class, 5)->make());
  }
}

这将按预期工作。

答案 2 :(得分:0)

尝试此方法:

        $users = factory(App\User::class, 5)->create();

    foreach ($users as $user) {
        $articles = factory(App\Article::class, 5)->create([
            'user_id' => $user->id
        ]);

        foreach ($articles as $article) {
            factory(App\Comment::class, 5)->create([
                'article_id' => $article['id']
            ]);
        }
    }