zoukankan      html  css  js  c++  java
  • YII2 models非常好用的控制输出数据【重写Fields】

    models里重写Fields真的很好用,用于分类、评论功能

    列子:评论表models/Comment.php

    1、关联商品表

    2、获取父级(即管理员)评论

    public function Fields()//添加parentComment自定义字段输出
    {
      $fields = parent::Fields();

      $fields['goods'] =function (self $model){
        return Material::find()->where(['id'=>$model->goods_id])->One();
      };//类似joinwith 表关联


      $fields['parentComment'] = function (self $model){
      return Comment::find()->where(['parent_id'=>$model->comment_id])->One();  // 获取父级评论
    };

    return $fields;
    }

    controller:

    $model = Comment::find()->where(['id'=>$id])->One();
    $model = $model->toArray();不知为什么 一定要toArray转换数组,fields才生效;知道的大神麻烦 留言,谢谢!

    可以在Fields做字段处理 输出到 controller,这样就减少controller的代码量 更能体现MVC模式!

  • 相关阅读:
    HTML/CSS
    Python字符编码
    软件测试遇到的问题积累
    数学
    经济学路谱
    工具
    DataStage
    Shell编程—定时任务
    WebLogic部署
    imageView-scaleType 图片压缩属性
  • 原文地址:https://www.cnblogs.com/jimz/p/7750060.html
Copyright © 2011-2022 走看看