本教程将指导您在YII模型中设置和自定义时间戳(create_at and Updated_at)。 YII提供了内置功能,可以自动管理这些时间戳,简化数据库交互并确保数据完整性。 我们将介绍各种方法和自定义选项。
created_at
yii提供了一种直接的方法,可以自动生成updated_at
>>behaviors
> TimestampBehavior
> timestamps。 这利用了处理这些属性的自动群体的
TimestampBehavior
来实现此功能,将behaviors()
添加到您的模型的
<?php namespace app\models; use yii\db\ActiveRecord; use yii\behaviors\TimestampBehavior; class MyModel extends ActiveRecord { public static function tableName() { return 'my_table'; } public function behaviors() { return [ TimestampBehavior::class, ]; } // ... other model code ... }
created_at
>> updated_at
>created_at
updated_at
此简单的添加自动在记录创建后自动填充了TIMESTAMP
。 该行为假设您的表具有合适的时间戳数据类型的DATETIME
和attributes
的列(例如,TimestampBehavior
,
public function behaviors() { return [ [ 'class' => TimestampBehavior::class, 'attributes' => [ ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'], ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'], ], //Optional: Customize value attribute (see next section for details) //'value' => new Expression('NOW()'), ], ]; }
>属性来指定它们:
TimestampBehavior
这允许在插入和更新事件期间更新哪些属性的细粒度控制。
beforeSave()
<?php namespace app\models; use yii\db\ActiveRecord; use yii\behaviors\TimestampBehavior; class MyModel extends ActiveRecord { public static function tableName() { return 'my_table'; } public function behaviors() { return [ TimestampBehavior::class, ]; } // ... other model code ... }
TimestampBehavior
doesn't directly allow customizing the TimestampBehavior
format将根据您的应用程序的设置格式化时间戳。
以上是yii框架时间戳怎么设置教程的详细内容。更多信息请关注PHP中文网其他相关文章!