問題描述
我正在嘗試添加與工廠模型的關系以進行一些數據庫播種,如下所示 - 請注意,我正在嘗試向每個用戶添加 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(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 個或發布給每個用戶,那么我必須聲明 10 或行,除非我使用某種 for 循環.
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());
});
}
* 更新 *
有沒有辦法把模型工廠嵌套到第三層深?
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());
}));
});
}
推薦答案
從 Laravel 5.6 開始就有回調函數 afterCreating &afterMaking 允許您在創建/制作后直接添加關系:
Since Laravel 5.6 there is a callback functions afterCreating & afterMaking allowing you to add relations directly after creation/make:
$factory->afterCreating(AppUser::class, function ($user, $faker) {
$user->saveMany(factory(AppPost::class, 10)->make());
});
$factory->afterMaking(AppPost::class, function ($post, $faker) {
$post->save(factory(AppComment::class)->make());
});
現在
factory(AppUser::class, 50)->create()
會給你 50 個用戶,每個用戶有 10 個帖子,每個帖子有一個評論.
will give you 50 users with each having 10 posts and each post has one comment.
這篇關于向 Laravel 工廠模型添加關系的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!