Yii2.0-advanced-5—行为的使用(自动生成model时间数据)

行为是 yii\base\Behavior 或其子类的实例。 行为,也称为 mixins, 可以无须改变类继承关系即可增强一个已有的 组件 类功能。 当行为附加到组件后,它将“注入”它的方法和属性到组件, 然后可以像访问组件内定义的方法和属性一样访问它们。 此外,行为通过组件能响应被触发的事件,从而自定义或调整组件正常执行的代码。

一、行为 Behavior 相关概念

1、行为的定义,

2、行为附加

3、行为使用

4、行为移除

5、处理事件

以上官方权威指南有详细讲解,http://www.yiichina.com/doc/guide/2.0/concept-behaviors

二、使用 timeStampBehavior

这个行为支持在 Active Record 存储时自动更新它的时间戳属性

namespace app\models\User;

use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;

class User extends ActiveRecord
{
    // ...

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
                // if you're using datetime instead of UNIX timestamp:
                // 'value' => new Expression('NOW()'),
            ],
        ];
    }
}

以上指定的行为数组:

  • 当记录插入时,行为将当前时间戳赋值给 created_at 和 updated_at 属性;
  • 当记录更新时,行为将当前时间戳赋值给 updated_at 属性。

注意:For the above implementation to work with MySQL database, please declare the columns(created_atupdated_at) as int(11) for being UNIX timestamp.

With that code in place, if you have a User object and try to save it, you will find its created_at and updated_at are automatically filled with the current UNIX timestamp:

$user = new User;
$user->email = 'test@example.com';
$user->save();
echo $user->created_at;  // 显示当前时间戳

TimestampBehavior 行为还提供了一个有用的方法 touch(), 这个方法能将当前时间戳赋值给指定属性并保存到数据库:

$user->touch('login_time');

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值