stores
table (id
, name
)
store_opening_hours
table (id
, store_id
, day_of_week
, opens_at
, closes_at
)
StoreFactory.php
file:
class StoreFactory extends Factory
{
public function definition(): array
{
return [
'name' => fake()->company
];
}
}
StoreOpeningHourFactory.php
file:
class StoreOpeningHourFactory extends Factory
{
public function definition(): array
{
return [
'store_id' => Store::factory(),
'day_of_week' => // What to put here?,
'opens_at' => fake()->time('H:i'),
'closes_at' => fake()->time('H:i'),
];
}
}
StoreSeeder.php
file:
class StoreSeeder extends Seeder
{
public function run(): void
{
Store::factory()
->has(StoreOpeningHour::factory()->count(7))
->create(10);
}
}
The day_of_week
will always be incrementing from [0-6]
for each store. How to do that inside StoreOpeningHourFactory.php
file?
2
Answers
You can utilize the sequence() method within StoreOpeningHourFactory.php, which is invoked from the StoreFactory class.
Note: You can initiate the sequence from the first argument and increment it by the second argument.
For instance, if you wish to start from 1 and increment by 1 for each subsequent item, you should utilize:
I hope this works as intended.
One idea is to use
But you can add only 7 rows, will also be awesome to store week_of_the_year
so you have unique on 2 columns
You also have some notes there
How to get unique values from faker?
Another implementation, you can use afterMaking callback, add an array of possible values and delete a random value from it, when array is empty get the default array