Defining Laravel foreign keys with Model Factories, One to One & One to Many Relationships without creating unnecessary models

后端 未结 2 1764
被撕碎了的回忆
被撕碎了的回忆 2021-02-13 22:54

Recently I have been trying to seed my database using Laravel seeding through Model Factories and Faker.

For simple schemas, it is just a breeze to have it working :). H

2条回答
  •  感动是毒
    2021-02-13 23:21

    So here is my solution:

    The example deals with:

    • Users & Profiles (for illustrating One to One relationships)
    • Users & Posts (for illustrating One to Many relationships)

      // ONE TO ONE relationship (with Users already created)
      $factory->define(App\Profile::class, function (Faker\Generator $faker) {
          return [
              'user_id' => $faker->unique()->numberBetween(1, App\User::count()),
              // Rest of attributes...
          ];
      });
      
      // ONE TO MANY relationship (with Users already created)
      $factory->define(App\Posts::class, function (Faker\Generator $faker) {
          $users = App\User::pluck('id')->toArray();
          return [
              'user_id' => $faker->randomElement($users),
              // Rest of attributes...
          ];
      });
      

提交回复
热议问题