添加新记录但时间字段应使用当前时间

Adding new record but time field should use current time

我正在使用 Cakephp 3.0.2。我想添加一条新记录。完整的记录 $this->request->data 看起来像这样;

'date_taken' => [
        'month' => '01',
        'day' => '05',
        'year' => '2015',
        'hour' => '02',
        'minute' => '51'
    ],  
    'moves_per_minute' => '80',
    'person_id' => '1'

但是,我希望 HTTP Post $this->request->data 看起来像这样;

'moves_per_minute' => '80',
'person_id' => '1'

dates_taken 数据应使用当前时间自动更新。

我将列 dates_taken 定义为 DATETIME 类型,默认为 CURRENT_TIME_STAMP。当我执行 HTTP Post 并发送 $this->request->data 并使 date_taken 为空时,无法添加新行。

这就是我的控制器代码的样子;

$newRecord = $this->newRecords->newEntity();
        if ($this->request->is('post')) {
            $newRecord = $this->newRecords->patchEntity($newRecord, $this->request->data);
            if ($this->newRecords->save($newRecord)) 
            {   
                //success
                Debugger::dump("Save success");
            } 
            else
            {
                $this->response->statusCode(400); //bad request      
                Debugger::dump("Save failure");
            }
        }     

一个正确的控制器应该是什么样子的?

将列 'created' 和 'modified' 添加到您的数据库 table(均为 DATETIME),然后在 table 的模型中添加此行:

class ArticlesTable extends Table
{
    public function initialize(array $config)
    {
        $this->addBehavior('Timestamp');
        // Timestamp is the correct, even though the field is a datetime
    }
}

添加新记录后,创建字段中存储的日期时间将是准确的创建时间,修改字段将是最后一次修改记录的时间。每次您通过实体访问此记录时,Cake 都会默认执行此操作。

可以通过此处的时间戳文档找到更多信息:http://book.cakephp.org/3.0/en/orm/behaviors/timestamp.html

您还可以使用时间库保存当前时间,保存前在实体中手动设置:

$time = Time::now();
$newRecord->date_taken = $time;

$this->newRecords->save($newRecord);

再次假设 date_taken 字段是 table 中的日期时间对象。不过,我建议让数据库为您设置它而不是这种方法。