I have a table of bugs, a table of actions and a history table.
Every time an action is performed on the bug I want to record it in my history table.
I'm trying to seed some dummy data to the database. This what I'm doing:
public function run()
{
$bugs = App\Bug::all();
foreach ($bugs as $bug) {
//Add a history entry for the bug
factory(App\History::class)->create([
'action_id' => App\Action::where('name', '=', 'create')->first()->id,
'user_id' => $bug->project->users->random()->id,
'bug_id' => $bug->id,
'created_at' => $bug->created_at,
'updated_at' => $bug->updated_at
]);
//Here I perform some random actions and save the history of the action
for ($i = 0; $i < 9; $i ++) {
$createdDate = $bug->created_at->addDays(mt_rand(1,6))->addHours(mt_rand(1,23))->toDateTimeString();
//This is the only action I'm having trouble with
factory(App\History::class, 1)->create([
'created_at' => $createdDate,
'action_id' => App\Action::where('name', '=', 'comment')->first()->id,
])->each(function ($history) {
$history->comment()
->save(factory(App\Comment::class)->make());
});
}
}
}
In my bug model factory I have
$factory->define(App\Bug::class, function (Faker\Generator $faker) {
return [
'name' => $faker->word,
'description' => $faker->sentence,
'project_id' => $faker->randomNumber(),
'created_at' => $faker->dateTimeBetween('-1 years'),
];
});
I'm expecting the above to store a history entry with the created_at field that is 1-5 days and 1-23 hours later than the bug's created_at field.
What I'm seeing is a random within the past year. As if I am doing this
$faker->dateTimeBetween('-1 years')
So sometimes I'm getting entries in my history table from before the creation entry.
I have hard coded in dates and it's storing it correctly.
It relates to https://stackoverflow.com/a/22968593/2344245. Since PHP 5+
By cloning them you get a new different instance. Therefore, this should work for you: