如何让多级工厂进行数据库播种工作

Mic*_*ell 3 php laravel-5

所以我试图让工厂设置为允许随机播种测试数据库.我希望能够创建一大堆用户,然后创建一堆房间,然后将评论发布到房间.

这就是我所拥有的:

factory('App\User', 5)->create()->each(function($u) {
    $u->rooms()->save(factory('App\Room', 10)->create()->each(function($p) {
        $p->posts()->save(factory('App\Post', 10)->make());
    }));
});
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, instance of Illuminate\Database\Eloquent\Collection given
Run Code Online (Sandbox Code Playgroud)

我假设错误意味着它在尝试创建帖子之前没有创建房间?

小智 6

也许有点晚了,但你必须调用saveMany(...)而不是如Eloquent 文档中 所述的save(...)

实际上,您想要创建多个对象(factory('App\Room', 10)->create()factory('App\Post', 10)->make()),它们返回一个Collection(简言之,一个对象数组)

特别感谢朋友,他提醒我RTM ^^