Search code examples
laravellaravel-seeding

Using model count in Laravel factory


I have a one to many relationship between User and Post. I am using a database seeder and factory to generate fake data. I would like to produce similar data to the following tables.

User

user_id | name
------- | ------
   1    | Tim

Post

post_id |  FK:user_id  | order 
--------|--------------|-------
   1    |       1      |   0  
   2    |       1      |   1   
   3    |       1      |   2   
   4    |       1      |   3   

To do this I created a factory that selects a random user and counts the number of posts associated with that user

$factory->define(App\Post::class, function (Faker\Generator $faker) {

  $user = App\User::inRandomOrder()->firstOrFail();
  $order = Post::where(['user_id' => $user->user_id])->count();

  return [
    'user_id' => $user->user_id,
    'order' => $order,
  ];
});

Seeding 2 post produces.

post_id |  FK:user_id  | order 
--------|--------------|-------
   1    |       1      |   0   
   2    |       1      |   0     

Seeding 2 more

   3    |       1      |   2   
   4    |       1      |   2   

It looks to me that Laravel is generating all of the insert statements before running the query. So Post::where(['user_id' => $user->user_id)->count(); doesn't increment as expected.

How do I increment Post.order so that it is always the next number in the sequence for a particular user?


Solution

  • You can always seed your data in a loop.

    for ($i = 0; $i < 10; $i++) {
        factory(App\Post::class)->create();
    }
    

    With the above, you are trying to insert 10 new Post objects. The sequence will be automatically incremented for each of those inserts