【问题标题】:Passing datetime string to laravel model factory chooses random date将日期时间字符串传递给 laravel 模型工厂选择随机日期
【发布时间】:2018-02-08 07:06:36
【问题描述】:

我有一个错误表、一个操作表和一个历史记录表。

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

我正在尝试将一些虚拟数据植入数据库。这就是我正在做的:

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



        }
    }
}

在我的错误模型工厂中,我有

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

我希望上面存储的历史记录条目的 created_at 字段比错误的 created_at 字段晚 1-5 天和 1-23 小时。

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

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

所以有时我会从创建条目之前获取历史表中的条目。

我对日期进行了硬编码,并且可以正确存储它。

【问题讨论】:

    标签: php laravel seeding


    【解决方案1】:

    它与https://stackoverflow.com/a/22968593/2344245 相关。自 PHP 5+ 起

    "对象默认通过引用传递"

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 2017-10-08
      • 2015-09-05
      • 2017-05-24
      相关资源
      最近更新 更多