向拉拉维尔工厂模型添加关系

2022-08-30 18:17:35

我正在尝试向工厂模型添加关系以执行一些数据库种子设定,如下所示 - 请注意,我正在尝试为每个用户添加2个帖子

public function run()
{
   factory(App\User::class, 50)->create()->each(function($u) {
         $u->posts()->save(factory(App\Post::class, 2)->make());
   });
}

但它抛出以下错误

Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::s  
ave() must be an instance of Illuminate\Database\Eloquent\Model, instance 
of Illuminate\Database\Eloquent\Collection given

我认为这与保存收藏有关。如果通过单独调用帖子的每个工厂模型来重写代码,它似乎可以正常工作。显然,这并不是很优雅,因为如果我想保留10或发布到每个用户,那么我必须标记10或行,除非我使用某种for循环。

public function run()
{
   factory(App\User::class, 50)->create()->each(function($u) {
     $u->posts()->save(factory(App\Post::class)->make());
     $u->posts()->save(factory(App\Post::class)->make());
   });
}

* 已更新 *

有没有办法将模型工厂嵌套在3rd级深度?

public function run()
{
   factory(App\User::class, 50)
       ->create()
       ->each(function($u) {
           $u->posts()->saveMany(factory(App\Post::class, 2)
                    ->make()
                    ->each(function($p){
                          $p->comments()->save(factory(App\Comment::class)->make());
          }));
   });
}

答案 1

从Laravel 5.6开始,在创建和之后有一个回调函数,允许您在创建/make之后直接添加关系:

$factory->afterCreating(App\User::class, function ($user, $faker) {
    $user->saveMany(factory(App\Post::class, 10)->make());
});

$factory->afterMaking(App\Post::class, function ($post, $faker) {
    $post->save(factory(App\Comment::class)->make());
});

现在

factory(App\User::class, 50)->create()

将为您提供50个用户,每个用户有10个帖子,每个帖子都有一条评论。


答案 2

试试这个。它对我有用:

factory(\App\Models\Auth\User::class, 300)->create()->each(function ($s) {
                    $s->spots()->saveMany(factory(\App\Models\Spots\Parking::class, 2)->create()->each(function ($u) {
                            $u->pricing()->save(factory(\App\Models\Payment\Pricing::class)->make());
                    }));
                    $s->info()->save(factory(\App\Models\User\Data::class)->make());
            });

推荐