Adding Relations to Laravel Factory Model
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(AppUser::class, 50)->create()->each(function($u) {
$u->posts()->save(factory(AppPost::class, 2)->make());
});
}
But its throwing the following error
Argument 1 passed to IlluminateDatabaseEloquentRelationsHasOneOrMany::s
ave() must be an instance of IlluminateDatabaseEloquentModel, instance
of IlluminateDatabaseEloquentCollection given
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(AppUser::class, 50)->create()->each(function($u) {
$u->posts()->save(factory(AppPost::class)->make());
$u->posts()->save(factory(AppPost::class)->make());
});
}
* UPDATED *
Is there any way to nest the model factory a 3rd level deep?
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());
}));
});
}
Try this. It worked for me:
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/87866.html
上一篇: 重复创建页面
下一篇: 添加关系到Laravel工厂模型