villers 2020-09-08 14:49:34 2444次浏览 3条回复 0 0 0

使用-数据转换无效

数据表有一个created字段,int类型,存的时间戳,类似1599195918

想在保存和读取的时候自己转换

实现了

public function getCreated(){
    return date('Y/m/d', $this->created);
}

最后查询

Category::find()
    ->all();

结果还是:1599195918

  • 回复于 2020-09-10 16:55 举报

    这个有两种情况:
    1.使用php在view中嵌套,渲染到模板的时候,例如你这里是list,渲染到Gridview中

    'columns' => [
        'article_id',
        [
            'attribute' => 'created'
            'value' => function($model){
                return date('Y/m/d', $this->created);
            }
        ]
    ]
    

    2.RestAPI中的字段格式化
    在ActiveRecord 模型中重写fields方法

    public function fields()
    {
        return [
          'articleId' => 'article_id',
          'created' => function($model){
              return date('Y/m/d', $this->created);
          }
        ];
    }
    
  • 回复于 2020-09-08 18:49 举报

    目前 用查询EVENT_AFTER_FIND事件回调处理,谁有更高效的方法 欢迎分享。

    $this->on(self::EVENT_AFTER_FIND,function ($event){
            $tm =$event->sender;
            $tm->created =  date('Y/m/d', $tm->created);
      });
    
    1 条回复
    回复于 2020-09-09 08:17 回复

    rules 的当然是输入的时候,afterFind 才是查询的时候啊~ 另外 afterFind 的原理应该于你的这个是一样的原理都是 trigger EVENT_AFTER_FIND 的事件

  • 回复于 2020-09-08 16:44 举报

    可以试试钩子 afterFind(),限制:只能使用 AR 的find,而不能使用 Query 或者 Connection

    public function afterFind(){
        parent::afterFind();
        $this->created = date('Y/m/d', $this->created);
    }
    

    参考链接: https://segmentfault.com/q/1010000009408189/a-1020000009411484

    1 条回复
    回复于 2020-09-08 18:30 回复

    你好,在验证规则里边处理数据好像只有输入的时候,执行验证才会触发。
    如果是从数据库读取数据好像不执行呢

您需要登录后才可以回复。登录 | 立即注册