1 回答

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
你必須使用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)返回一個(gè)集合而不是模型,這將引發(fā)異常,我將其替換為Model::inRandomOrder()->first(),它將從數(shù)據(jù)庫(kù)中獲取一個(gè)隨機(jī)模型。
從文檔:
更新 belongsTo 關(guān)系時(shí),可以使用 associate 方法。此方法將在子模型上設(shè)置外鍵:
$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;
},
];
});
在你的播種機(jī)中:
public function seed()
{
factory(User::class, 10)->create();
factory(Category::class, 10)->create();
factory(Post::class, 100)->create();
}
- 1 回答
- 0 關(guān)注
- 128 瀏覽
添加回答
舉報(bào)