从Carbon和Laravel创建额外用户

时间:2017-08-21 22:05:47

标签: laravel laravel-5.3 php-carbon

我试图弄清楚为什么当我运行这个种子文件时,它会在正确的日期创建50,但是它仍然会在同一天创建另外4个它不应该。它应该从原始开始日期开始增加4个月,然后每4个月开始做5个用户。任何人都能看到我做错了什么?

    $startingDate = Carbon::parse('First Monday of January 2010');
    $hiringDays = new DatePeriod(
        $startingDate->addMonths(4),
        CarbonInterval::months(4),
        Carbon::now()
    );

    $userCount = 1;
    for ($userCount; $userCount < 50; $userCount++) {
        factory(User::class)->create([
            'hired_at' => $startingDate,
        ]);
    }

    foreach ($hiringDays as $day)
    {
        for ($x = 1; $x <= 5; $x++) {
            factory(User::class)->create([
                'hired_at' => $day,
            ]);
            $this->userCount++;
        }
    }

1 个答案:

答案 0 :(得分:0)

您可以尝试使用while循环而不是DatePeriod

$hireDate = Carbon::parse('First Monday of January 2010');
$limit = $startingDate->copy()->addMonths(4);

while( $startingDate->lte( limit ) ){
    factory(User::class)->create([
        'hired_at' => $startingDate,
    ]);
    $this->userCount++;
    $startingDate->addMonth();
}