how to use mysql now() function in cakephp for date fields?

后端 未结 5 1699
我寻月下人不归
我寻月下人不归 2021-01-21 12:02

I have this code in my cakephp project:

$this->data[\'MyObject\'][\'expire_date\'] = \'NOW()\';

and...

$this->MyObject-&g         


        
相关标签:
5条回答
  • 2021-01-21 12:25

    For CakePHP 3 (in case someone's searching), you'd need to use the SQL functions:

    $query = $this->Example->query();
    $query
        ->insert(['created','id'])
        ->values(array(
            'created' => $query->func()->now(),
            'id' => $id,
        ));
    $result = $query->execute();
    

    Sources:

    • query-builder.html#using-sql-functions
    0 讨论(0)
  • 2021-01-21 12:35

    For cakephp 2.x users:

    $db = $this->MyObject->getDataSource(); 
    
    
    $this->data['MyObject']['expire_date'] = $db->expression('NOW()');
    
    0 讨论(0)
  • 2021-01-21 12:38
    $this->data['MyObject']['expire_date'] = DboSource::expression('NOW()');
    
    0 讨论(0)
  • 2021-01-21 12:44
    $this->data['MyObject']['expire_date'] = strtotime('now');
    
    0 讨论(0)
  • 2021-01-21 12:45

    You can shorten that to

    $this->data['MyObject']['expire_date'] = date('Y-m-d H:i:s'); 
    

    By default, date() will take the present time, if you do not pass it a second 'timestamp' argument.

    This method is preferable to calling DboSource::expression() especially when you want to set it in the controller for various reasons, instead of in the model.

    0 讨论(0)
提交回复
热议问题