3

我想用 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 行:调用未定义的方法 Illuminate\Database\Query\Builder::save()

4

3 回答 3

1

尝试这个 :

$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());
}
于 2017-12-12T15:07:38.877 回答
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']
            ]);
        }
    }
于 2019-03-03T10:23:51.953 回答
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());
  }
}

这将按预期工作。

于 2018-10-27T21:33:52.163 回答