本教程將指導您在YII模型中設置和自定義時間戳(create_at and Updated_at)。 YII提供了內置功能,可以自動管理這些時間戳,簡化數據庫交互並確保數據完整性。 我們將介紹各種方法和自定義選項。
created_at
yii提供了一種直接的方法,可以自動生成updated_at
>>behaviors
> TimestampBehavior
> timestamps。 這利用了處理這些屬性的自動群體的
TimestampBehavior
來實現此功能,將behaviors()
添加到您的模型的
<code class="php"><?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 ... }</code>
created_at
>> updated_at
>created_at
updated_at
此簡單的添加自動在記錄創建後自動填充了TIMESTAMP
。 該行為假設您的表具有合適的時間戳數據類型的DATETIME
和attributes
的列(例如,TimestampBehavior
,
<code class="php">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()'), ], ]; }</code>>配置中的
>屬性來指定它們:
TimestampBehavior
這允許在插入和更新事件期間更新哪些屬性的細粒度控制。
beforeSave()
<code class="php"><?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 ... }</code>>使用自定義行為:
TimestampBehavior
doesn't directly allow customizing the TimestampBehavior
format將根據您的應用程序的設置格式化時間戳。
以上是yii框架時間戳怎麼設置教程的詳細內容。更多資訊請關注PHP中文網其他相關文章!