Laravel, Faker - Increment generated dateTime

依然范特西╮ 提交于 2019-12-06 10:45:33

问题


I'm using Faker package in my Seeder to generate fake data for training events.

Each event has starts_at and ends_at fields. I want to populate the ends_at field with a DateTime that is after the one generated for starts_at, preferably by 1 to 8 hours, or even a fixed 1 hour difference would be fine.


回答1:


here is an easy way to define the ends_at

$starts_at = Carbon::createFromTimestamp($faker->dateTimeBetween($startDate = '+2 days', $endDate = '+1 week')->getTimeStamp()) ;

$ends_at= Carbon::createFromFormat('Y-m-d H:i:s', $starts_at)->addHours( $faker->numberBetween( 1, 8 ) );



回答2:


Adapting the pattern described in Build APIs You Won't Hate and using the awesome Carbon package, here's how you can do it:

<?php

use Carbon\Carbon;
use Faker\Factory as Faker;

class UserEventsTableSeeder extends Seeder {

    public function run() {
        $faker = Faker::create();

        foreach (range(1, 15) as $index) {
            $startDate = Carbon::createFromTimeStamp($faker->dateTimeBetween('-1 years', '+1 month')->getTimestamp());

            UserEvent::create([
                // ...

                'starts_at' => $startDate->toDateTimeString(),
                'ends_at'   => $startDate->addHours( $faker->numberBetween( 1, 8 ) )
            ]);
        }
    }
}


来源:https://stackoverflow.com/questions/26700446/laravel-faker-increment-generated-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!