问题
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