douke9379 2019-03-28 14:30
浏览 787
已采纳

如何使用faker dateTimeBetween创建虚假事件?

I am trying to create a Factory in Laravel that will fake an event created on a calendar. The event has a Start DateTime and End DateTime. I want the start date to be sometime in the future from now and the end dateTime to be within a few hours of the start dateTime. I keep getting the same dateTime on both start and end.

I have tried a few different methods that I found from Google and they all result in both the start and end dateTimes being identical.

use Faker\Generator as Faker;

$factory->define(App\Event::class, function (Faker $faker) {

    $start_date = $faker->dateTimeBetween('+0 days', '+1 month');
    $end_date = $faker->dateTimeBetween($start_date, $start_date->modify('+5 hours'));

    $user = factory(App\User::class)->create();

    return [
        'name' => $faker->sentence,
        'description' => $faker->paragraph,
        'start_date_time' => $start_date,
        'end_date_time' => $end_date,
        'owner_id' => $user->id,
        ];
});

I expect the start DateTime to be between now and 1 month and, I expect the end DateTime to be between the start dateTime and 5 hours later.

  • 写回答

1条回答 默认 最新

  • dongxing5525 2019-03-28 15:18
    关注

    Your problem is actually pretty straight forward to identify. You're using the same instance stored in $start_date in multiple places, which means that any change to that instance will be reflected in all places because:

    In PHP objects are passed by reference

    This means that if you create an instance of DateTime stored in $start_date and then you call $start_date->modify() that will modify the value and will be reflected in all places in which the variable is referenced.

    So you're essentially passing the same two modified $start_date values to generate the $end_date value, which is why you get the same date for both range edges.


    To fix the reference issue you should create a clone of your $start_date and call modify on that to avoid modifying the original value:

    $start_date = $faker->dateTimeBetween('+0 days', '+1 month');
    $start_date_clone = clone $start_date;
    
    $end_date = $faker->dateTimeBetween($start_date, $start_date_clone->modify('+5 hours'));
    

    To mitigate the reference issues, PHP 5.5 introduced DateTimeImmutable which does not apply changes to itself. However, Faker's implementation of dateTimeBetween specifically checks if the instances passed to the method are of DateTime object (or just plain datetime strings that it can feed to strtotime()), so it doesn't work with DateTimeImmutable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面