Yii2添加timestamp字段报timestamps()未定义错误解决
Yii2迁移报Call to undefined function timestamps() 解决方法
报错原因
timestamps()是Laravel框架迁移的内置方法,Yii2的yii\db\Migration迁移类没有提供这个方法,也不存在同名全局函数,调用后就会触发未定义函数异常。- 你贴出的示例代码里写的是带
$this->前缀的单数形式timestamp(),实际运行报错的代码里,要么漏写了$this->前缀把方法当成全局函数调用,要么把方法名错拼成了复数形式timestamps()。
修正后的完整迁移代码
直接使用Yii2内置的$this->timestamp()方法定义时间戳字段即可,补全缺失的回滚方法后代码如下:
<?php use yii\db\Migration; /** * Handles the creation of table `{{%reporting}}`. */ class m220510_213949_create_reporting_table extends Migration { /** * {@inheritdoc} */ public function safeUp() { $this->createTable('{{%reporting}}', [ 'id' => $this->primaryKey(), 'id_user' => $this->integer()->notNull(), 'link' => $this->text()->notNull()->unique(), 'note' => $this->text()->notNull(), 'state' => "ENUM('Sent','In processing','Analyzed','Error') NOT NULL", 'sent_date_analysis' => $this->timestamp(), 'start_date_analysis' => $this->timestamp(), 'end_date_analysis' => $this->timestamp(), ]); } /** * {@inheritdoc} */ public function safeDown() { $this->dropTable('{{%reporting}}'); } }
补充说明
- 如果需要给timestamp字段设置默认值,可以链式调用
defaultExpression()方法实现,比如设置字段默认值为当前时间:$this->timestamp()->defaultExpression('CURRENT_TIMESTAMP'),需要自动更新为当前时间可以用$this->timestamp()->defaultExpression('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')。 - 跨数据库兼容场景下更推荐用integer类型字段存Unix时间戳,配合模型层的
TimestampBehavior自动维护创建、更新时间,能避免不同数据库对timestamp类型的实现差异导致的异常。
内容的提问来源于stack exchange,提问作者WorraccCdP
相关产品推荐
相关产品推荐

