21
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel Faker で 日付ダミーデータ間の整合性を取る

Posted at

$fakerでdateTimeのダミーデータの整合性を取りたい

./database/factory/PlanFactory.php
use Faker\Generator as Faker;

$factory->define(\App\Plan::class, function (Faker $faker) {
    return [
        //
        [
            'start_datetime'=>$faker->dateTimeBetween('1day', '1year')->format('Y-m-d H:i'),
            'end_datetime'=> $faker->dateTimeBetween('1day', '1year')->format('Y-m-d H:i'),
        ]
    ];
});

ダミーデータでstart_at とend_atの値がランダムになってしまうためend_at はstart_at の1~2時間後に値を設定したい。

Faker dateTimeBetweenの戻り値はDatetime型

vendor\fzaninotto\faker\src\Faker\Provider\DateTime.php
    /**
     * Get a DateTime object based on a random date between two given dates.
     * Accepts date strings that can be recognized by strtotime().
     *
     * @param \DateTime|string $startDate Defaults to 30 years ago
     * @param \DateTime|string $endDate   Defaults to "now"
     * @param string|null $timezone time zone in which the date time should be set, default to DateTime::$defaultTimezone, if set, otherwise the result of `date_default_timezone_get`
     * @example DateTime('1999-02-02 11:42:52')
     * @return \DateTime
     * @see http://php.net/manual/en/timezones.php
     * @see http://php.net/manual/en/function.date-default-timezone-get.php
     */
    public static function dateTimeBetween($startDate = '-30 years', $endDate = 'now', $timezone = null)
    {
        $startTimestamp = $startDate instanceof \DateTime ? $startDate->getTimestamp() : strtotime($startDate);
        $endTimestamp = static::getMaxTimestamp($endDate);

        if ($startTimestamp > $endTimestamp) {
            throw new \InvalidArgumentException('Start date must be anterior to end date.');
        }

        $timestamp = mt_rand($startTimestamp, $endTimestamp);

        return static::setTimezone(
            new \DateTime('@' . $timestamp),
            $timezone
        );
    }

なので、日付を一度$fakerで作成し、メモリに持ち、意図する日付に修正するように変更しました。

use Faker\Generator as Faker;

$factory->define(\App\Plan::class, function (Faker $faker) {
    $scheduled_date = $faker->dateTimeBetween('+1day', '+1year');
    
    return [
        'start_datetime'=>$scheduled_date->format('Y-m-d H:i:s'),
        'end_datetime'=> $scheduled_date->modify('+1hour')->format('Y-m-d H:i:s'),
        'remind_at'=>$scheduled_date->modify('-1day')->format('Y-m-d H:i:s'),
    ];
});

これで faker で作る日付データの整合性が取れました。

以上です。

21
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?