使用模型工厂播种多对多关系

时间:2020-04-28 15:59:34

标签: laravel-6 faker laravel-seeding

我有一个以下的模型工厂,与个人档案和行业有很多联系。当我运行播种机时,将创建一个求职者并创建了配置文件,但是afterCreating配置文件回调内部的所有行业都没有保存?

$factory->define(App\Jobseeker::class, function (Faker $faker) {
     return [
        'user_id' => factory('App\User')->create()->id
     ];
});

$factory->afterCreating(App\Jobseeker::class, function ($jobseeker, $faker) {
    $jobseeker->profile()->save(factory(App\Profile::class)->make());
});

$factory->afterCreating(App\Profile::class, function ($profile, $faker) {

     $profile->industries()->sync(App\Industry::inRandomOrder()->limit(2)->pluck('id')->all());
});

这就是我所说的:

factory(App\Jobseeker::class, 50)->create();

任何帮助表示赞赏。

0 个答案:

没有答案