将日期时间字符串传递给laravel模型工厂选择随机日期

时间:2017-08-30 14:03:26

标签: php laravel seeding

我有一张错误表,一个行动表和一张历史表。

每次对错误执行操作时,我都要将其记录在历史记录表中。

我试图将一些虚拟数据播种到数据库中。这就是我正在做的事情:

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());
                    });



        }
    }
}

在我的bug模型工厂中我有

$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'),
];
});

我希望上面的内容能够存储一个history_at字段的历史记录条目,该字段比bug的created_at字段晚1-5天和1-23小时。

我在过去一年中看到的是一个随机的。好像我在做这个

$faker->dateTimeBetween('-1 years')

因此,有时我会在创建条目之前的历史记录表中获取条目。

我在日期中进行了硬编码,并且正确存储了它。

1 个答案:

答案 0 :(得分:0)

它与https://stackoverflow.com/a/22968593/2344245有关。自PHP 5+以来

  

&#34;对象默认通过引用传递&#34;

通过克隆它们,您将获得一个新的不同实例。因此,这应该适合你:

$createdDate = $bug->created_at->copy()->addDays(mt_rand(1,6))->addHours(mt_rand(1,23))->toDateTimeString();