【问题标题】:Save multiple records created from a range of dates in CakePHP 2.x在 CakePHP 2.x 中保存从一系列日期创建的多条记录
【发布时间】:2016-02-01 23:16:48
【问题描述】:

我必须获取用户选择的开始和结束日期的日期范围,检查日期不属于周末和/或公共假期,并将每个有效日期插入数据库,直到结束日期。

下面是我的代码:

$aryRange=array();

$istartTime=mktime(1,0,0,substr($startTime,5,2),     substr($startTime,8,2),substr($startTime,0,4));
$iendTime=mktime(1,0,0,substr($endTime,5,2),     substr($endTime,8,2),substr($endTime,0,4));

if ($iendTime>=$istartTime)
{
    array_push($aryRange,date('Y-m-d',$istartTime)); // first entry
    while ($istartTime<$iendTime)
    {
        $istartTime+=86400; // add 24 hours
        array_push($aryRange,date('Y-m-d',$istartTime));
    }
}

$aryRange = array_values($aryRange);

$dates = array($aryRange);

$fdate = strtotime($startTime);
$day = date("N",$fdate);


$holidays = $this->Leave->PublicHoliday->find ('all', array('fields'=>array('PublicHoliday.SetDate')));


foreach($dates as $key => $value)
{
    if ($day == 7 || $day == 6)
    {
        unset ($dates[$k]);
        continue;

    }
    if (in_array($value, $holidays))
    {
        unset ($dates[$k]);
        continue;
    }

}

我不知道如何为每个条目分配开始日期和结束日期并保存数据。我认为这可以在foreach 循环中完成。

$this->request->data['Leave']['event_date'] = $value[0];
$this->request->data['Leave']['event_stop_time'] = $value[0];
$this->Leave->save($this->request->data);

我可以在foreach 循环执行时逐行保存吗?非常感谢任何有关保存数据的帮助。

注意: event_date 将类似于 event_stop_time 一天。

【问题讨论】:

  • 你用的是什么版本的蛋糕?如果没有这个,我真的无法为您提供一个很好的答案。

标签: php datetime cakephp cakephp-2.5 cakephp-2.x


【解决方案1】:

尝试以下方法:

$period = new DatePeriod(new DateTime($istarTime), new DateInterval('P1D'), new DateTime($iendTime));
$holidays = $this->Leave->PublicHoliday->find('list', array('fields'=>array('PublicHoliday.SetDate')));

foreach ($period as $date) {
    if ($date->format('N') < 6 && !in_array($date->format('Y-m-d'), $holidays)) {
        $data[] = ['Leave' => [
            'event_date' => $date->format('Y-m-d'),
            'event_stop_time' => $date->format('Y-m-d'),
        ]];
    }
}

$this->Leave->saveMany($data);

如果PublicHoliday.SetDate 是您数据库中的DATE 字段,则上述内容应该有效。

【讨论】:

    猜你喜欢
    • 2011-05-14
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2016-08-20
    • 1970-01-01
    • 2017-08-20
    • 2015-07-29
    相关资源
    最近更新 更多