factoryでリレーション を持たせてモデルを生成する方法
状況
userモデルのリレーション先であるuser_profileのuser_idにuserモデルのidを持たせたい
user_profileのfactoryはこんな感じ
<?php /** @var \Illuminate\Database\Eloquent\Factory $factory */ use App\Model\UserProfile; use Faker\Generator as Faker; $factory->define(UserProfile::class, function (Faker $faker) { return [ 'user_id' => function() { //ここからがポイント return factory(App\User::class)->create()->id; }, 'user_name' => $faker->userName(), 'residence' => "東京都", 'age' => rand(20,30), 'job' => $faker->jobTitle, 'img_url' => "https://matching-kou.s3.ap-northeast-1.amazonaws.com/3/TW2fauu9FNUFIYorYS8zqcSee1w2V6HPR36uJKOj.png", 'text' => $faker->text(100), ]; });
- facotryを生成する時にこんな感じで書くけばいい
<?php factory(User::class, 6)->create()->each(function ($user) { factory(UserProfile::class, 1)->create(['user_id' => $user->id, 'age' => "25"]); });