向Laravel Factory模型添加关系 [英] Adding Relations to Laravel Factory Model

查看:103
本文介绍了向Laravel Factory模型添加关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to add a relation to a factory model to do some database seeding as follows - note I'm trying to add 2 posts to each user

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个或向每个用户发布内容,那么除非我使用某种for循环,否则我必须减少10个或10行的比例.

I think its something to do with saving a collection. If re-write the code by calling each factory model for the post separately it seems to work. Obviously this isn't very elegant because if I want to persist 10 or post to each user then I'm having to decalare 10 or lines unless I use some kind of for loop.

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

*更新*

有什么方法可以将模型工厂嵌套到第3层吗?

Is there any way to nest the model factory a 3rd level deep?

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

推荐答案

尝试一下.它对我有用:

Try this. It worked for me:

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

这篇关于向Laravel Factory模型添加关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆