php Yii2,如何使用 yii/db/Migration 将当前时间插入日期时间字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42080266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:32:21  来源:igfitidea点击:

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

phpyii2

提问by Jeremiah Tenbrink

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

我正在使用 Yii 2 框架并且我正在创建一个迁移文件。在此迁移中,我尝试使用以下方法将记录插入表中

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

The column name I'm trying to update without success is the created_atand updated_atfields that are currently the type of datetimewith nullset 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.

我试图更新没有成功的列名是created_atupdated_at是当前的类型字段datetimenull设置为Yes。我可以将列的默认属性设置为当前时间戳。但是,我不是创建数据库的人,也不愿意修改表方案。我尝试了许多不同的方法来将日期时间字段设置为当前日期时间,但没有成功。附上我拥有的当前代码和当前表方案的两个屏幕截图。

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

提前为新手问题道歉。任何帮助将不胜感激,请和谢谢。

yii/db/Migration code

yii/db/迁移代码

table

桌子

回答by Bizley

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

您确定要以这种格式存储日期吗?通常 UNIX 时间戳更加灵活。

Anyway you can use plain PHP method like:

无论如何,您可以使用普通的 PHP 方法,例如:

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

or expression:

或表达:

'created_at' => new \yii\db\Expression('NOW()'),