1 回答
TA贡献1794条经验 获得超7个赞
你必须使用associate():
public function seed()
{
factory(User::class, 10)->create();
factory(Category::class, 10)->create();
factory(Post::class, 100)->make()->each(function ($post) {
$post->user()->associate(User::inRandomOrder()->first());
$post->category()->associate(Category::inRandomOrder()->first());
$post->save();
});
}
还将User::all()->random(1)返回一个集合而不是模型,这将引发异常,我将其替换为Model::inRandomOrder()->first(),它将从数据库中获取一个随机模型。
从文档:
更新 belongsTo 关系时,可以使用 associate 方法。此方法将在子模型上设置外键:
$account = App\Account::find(10);
$user->account()->associate($account);
$user->save();
更新
在您的模型工厂中:
/** @var Factory $factory */
$factory->define(Post::class, function (Faker\Generator $faker) {
return [
// not sure why you do this, is it not a autoincrement column?
'id' => $faker->unique()->randomNumber(3),
'name' => $faker->realText($maxNbChars = 200, $indexSize = 2),
'category_id' => function () {
if ($category = Category::inRandomOrder()->first()) {
return $category->id;
}
return factory(Category::class)->create()->id;
},
'user_id' => function () {
if ($user = User::inRandomOrder()->first()) {
return $user->id;
}
return factory(User::class)->create()->id;
},
];
});
在你的播种机中:
public function seed()
{
factory(User::class, 10)->create();
factory(Category::class, 10)->create();
factory(Post::class, 100)->create();
}
- 1 回答
- 0 关注
- 86 浏览
添加回答
举报