向拉拉维尔工厂模型添加关系
2022-08-30 18:17:35
我正在尝试向工厂模型添加关系以执行一些数据库种子设定,如下所示 - 请注意,我正在尝试为每个用户添加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或发布到每个用户,那么我必须标记10或行,除非我使用某种for循环。
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());
});
}
* 已更新 *
有没有办法将模型工厂嵌套在3rd级深度?
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());
}));
});
}