0

I have a table users in a one-many relationship with a table called videos. I want to seed the two table without loosing data integrity. This is what I did below:

$factory->define(App\User::class, function (Faker\Generator $faker) {
return [
    'name' => $faker->name,
    'email' => $faker->email,
    'username' => $faker->unique()->userName
];
});

$factory->define(App\Video::class, function(Faker\Generator $faker){
    $user = factory(App\User::class)->create();
    return [
        'title' => $faker->city,
        'link' => $faker->domainName,
        'user_id' => $user->id,
        'description' => $faker->sentence(40)
    ];
});

So now all I have to do is create a VideoTableSeeder and run the amount I want. I feel like the way I am handling it is not good enough so I would like to know what better way I can do it. Especially, I want the videos to be more than users rather than the same amount, in the one I had done they will all be the same amount.

George
  • 3,757
  • 9
  • 51
  • 86

1 Answers1

0

Checkout the documentation the section Adding Relations to Models

Adding Relations To Models

You may even persist multiple models to the database. In this example, we'll even attach a relation to the created models. When using the create method to create multiple models, an Eloquent collection instance is returned, allowing you to use any of the convenient functions provided by the collection, such as each:

$users = factory(App\User::class, 3) ->create() ->each(function($u) { $u->posts()->save(factory(App\Post::class)->make()); });

Mark Davidson
  • 5,503
  • 5
  • 35
  • 54