Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2, how do I insert the current time into a date time field using yii/db/Migration?

Tags:

php

yii2

I'm using the Yii 2 framework and I am creating a migration file. In this migration I am trying to insert a record into a table using

$this->insert('table_name', ['column_name'=> time]); 

The column name I'm trying to update without success is the created_at and updated_at fields that are currently the type of datetime with null set to Yes. I could just set the default attribute of the column to current timestamp. However I am not the one that created the database and am reluctant on modifying the table scheme. I have tried many different ways to set the datetime field to the current datetime with no luck. Attached are two screenshots of the current code I have and the current table scheme.

Apologize in advance for the newb question. Any help would be greatly appreciated, please and thank you.

yii/db/Migration code

table

like image 590
Jeremiah Tenbrink Avatar asked Feb 07 '17 01:02

Jeremiah Tenbrink


People also ask

How can I get current date in yii?

You can get this through php by using date('Y-m-d h:i:s') or date($format) where $format contains the format in which you want the time. This by default gives you date and time for now.

What is migration in yii?

Yii provides the database migration feature that allows you to keep track of database changes. Yii provides the following migration command line tools − Create new migrations. Revert migrations. Apply migrations.

How do I run a specific migration in yii2?

To run specific migration, you can mark(skip) migrations upto just before one you want run. You can mark migration by using one of following command: Using timestamp to specify the migration yii migrate/mark 150101_185401. Using a string that can be parsed by strtotime() yii migrate/mark "2015-01-01 18:54:01"


1 Answers

Are you sure you want to store dates in this format? Usually UNIX timestamp is much more flexible.

Anyway you can use plain PHP method like:

'created_at' => date('Y-m-d H:i:s'),

or expression:

'created_at' => new \yii\db\Expression('NOW()'),
like image 182
Bizley Avatar answered Oct 26 '22 22:10

Bizley