我有User
和Activity
模型。 User
与Activity
有很多关系(并且Activity
属于仅一个User
):
在用户模型中:
public function activities() {
return $this->hasMany(Activity::class);
}
我想为用户提供相应的活动。我试过了,但是没用:
public function run()
{
factory(App\User::class, 5)->create()->each(function ($user) {
$user->activities()->saveMany(factory(App\Activity::class, 2)->make());
});
}
ActivityFactory:
$factory->define(App\Activity::class, function (Faker $faker) {
return [
'title' => $faker->text(50),
'description' => $faker->text(200)
];
});
我在做什么错了?
答案 0 :(得分:4)
尝试这种方式:
database / factories / ActivityFactory.php
$factory->define(App\Activity::class, function (Faker\Generator $faker) {
return [
'user_id' => factory('App\User')->create()->id,
'title' => $faker->text(50),
'description' => $faker->text(200),
];
});
数据库/种子/ActivitySeeder.php
public function run()
{
factory(App\Activity::class, 10)->create();
}
然后运行活动种子。
php artisan make:seeder ActivitySeeder