gpt4 book ai didi

relationship - 向Laravel Factory模型添加关系

转载 作者:行者123 更新时间:2023-12-03 21:25:05 24 4
gpt4 key购买 nike

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

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

*更新*

有什么方法可以将模型工厂嵌套到第三层深度?
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());
}));
});
}

最佳答案

从Laravel 5.6开始,有一个回调函数afterCreating & afterMaking允许您在创建/制作之后直接添加关系:

$factory->afterCreating(App\User::class, function ($user, $faker) {
$user->saveMany(factory(App\Post::class, 10)->make());
});

$factory->afterMaking(App\Post::class, function ($post, $faker) {
$post->save(factory(App\Comment::class)->make());
});

现在
factory(App\User::class, 50)->create()

将为您提供50位用户,每位用户有10条帖子,每条帖子都有一条评论。

关于relationship - 向Laravel Factory模型添加关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32540845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com