Submitting current timestamp in CakePHP
-
26-09-2019 - |
Question
What is the method to submit a current timestamp directly on an INSERT
or an UPDATE
? If I were running regular SQL, I would use the function NOW()
for the specific SQL field on submission. How would I do that with CakePHP?
$this->Model->save($this->data)
Solution
In CakePHP, you can include the NOW()
function unescaped by using DboSource::expression
$this->data['SomeModel']['your_datetime_field'] = DboSource::expression('NOW()');
$this->Model->save($this->data);
This is the preferred way of including MySQL functions in your saves.
OTHER TIPS
if you add the created and modified columns in you table they will be automatically populated with current time stamp. If the case is different - i.e. you want to populate a field which later on you want to modify, probably using the edorian's solution is best.
You can set timestamp field to auto initialize and auto update
timestampfield TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow