添加关系到Laravel工厂模型

我试图添加一个关系到一个工厂模型做一些数据库种子如下 - 注意我试图给每个用户添加2个职位

public function run()
{
   factory(AppUser::class, 50)->create()->each(function($u) {
         $u->posts()->save(factory(AppPost::class, 2)->make());
   });
}

但它抛出以下错误

Argument 1 passed to IlluminateDatabaseEloquentRelationsHasOneOrMany::s  
ave() must be an instance of IlluminateDatabaseEloquentModel, instance 
of IlluminateDatabaseEloquentCollection given

我认为它与保存一个集合有关。 如果通过分别调用每个工厂模型来重新编写代码,它似乎可以工作。 显然这不是很优雅,因为如果我想坚持10或发布给每个用户,那么我不得不decalare 10或行,除非我使用某种for循环。

public function run()
{
   factory(AppUser::class, 50)->create()->each(function($u) {
     $u->posts()->save(factory(AppPost::class)->make());
     $u->posts()->save(factory(AppPost::class)->make());
   });
}

* 更新 *

有没有什么办法可以将模型工厂嵌入第三层?

public function run()
{
   factory(AppUser::class, 50)
       ->create()
       ->each(function($u) {
           $u->posts()->saveMany(factory(AppPost::class, 2)
                    ->make()
                    ->each(function($p){
                          $p->comments()->save(factory(AppComment::class)->make());
          }));
   });
}

尝试这个。 它为我工作:

factory(AppModelsAuthUser::class, 300)->create()->each(function ($s) {
                    $s->spots()->saveMany(factory(AppModelsSpotsParking::class, 2)->create()->each(function ($u) {
                            $u->pricing()->save(factory(AppModelsPaymentPricing::class)->make());
                    }));
                    $s->info()->save(factory(AppModelsUserData::class)->make());
            });

对于第三级嵌套关系,如果要使用适当的相应外键创建数据,则可以循环创建帖子的所有结果,如下所示:

factory(AppUser::class, 50)->create()->each(function($u) {
    $u->posts()
        ->saveMany( factory(AppPost::class, 2)->make() )
        ->each(function($p){
            $p->comments()->save(factory(AppComment::class)->make());
        });
});
链接地址: http://www.djcxy.com/p/87865.html

上一篇: Adding Relations to Laravel Factory Model

下一篇: Getting CPU usage of a specific Service in C#