You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel中向availability表插入开始时间与结束时间

向availability表批量插入每日时段记录

我需要向availability表中插入**开始时间(startdatetime)和结束时间(enddatetime)**记录,要求如下:

  • 覆盖时段:从2023-01-27 10:00:00到2023-02-25 12:00:00
  • 每日固定时段:当日10:00:00开始,12:00:00结束
  • 关联固定用户ID(示例中为2)

表结构

编号用户ID开始时间结束时间
122023-01-27 10:00:002023-01-27 12:00:00
122023-01-28 10:00:002023-01-28 12:00:00
122023-01-29 10:00:002023-01-29 12:00:00
122023-01-30 10:00:002023-01-30 12:00:00
122023-01-31 10:00:002023-01-31 12:00:00
122023-02-01 10:00:002023-02-01 12:00:00

现有代码问题

给出的循环插入代码存在两处关键问题:

  1. 结束时间直接复用了开始时间的日期时间值,没有设置为当日12:00:00
  2. 循环终止条件如果用完整的日期时间对象比较,可能导致循环范围不符合预期

修正后的代码

// 初始化开始日期(带当日起始时间)和结束日期(仅日期部分,避免时间干扰循环判断)
$begin = new DateTime('2023-01-27 10:00:00');
$endDate = new DateTime('2023-02-25');

// 遍历每一天生成记录
for ($currentDate = $begin; $currentDate <= $endDate; $currentDate->modify('+1 day')) {
    // 构造当日的起止时间字符串
    $startDateTime = $currentDate->format('Y-m-d') . ' 10:00:00';
    $endDateTime = $currentDate->format('Y-m-d') . ' 12:00:00';

    $_attribute = [
        'start_date_time' => $startDateTime,
        'end_date_time'   => $endDateTime,
        'user_id'         => $user->id
    ];

    \App\models\availability::create($_attribute);
}

修正说明

  • 拆分起止时间构造:单独生成当日10点和12点的时间字符串,确保时段正确
  • 调整循环终止判断:用仅含日期的对象作为结束条件,保证循环覆盖到2023-02-25当天
  • 优化数组写法:使用PHP短数组语法,代码更简洁

内容的提问来源于stack exchange,提问作者coreaccess

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 17:56:06