Using model count in Laravel factory

Viewed 2451

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?

1 Answers
Related