zoukankan      html  css  js  c++  java
  • YII2框架动态创建表模型

    YII2框架动态创建表模型

    在YII2中,每个表对应一个model类

    在开发过程中,我们在填写一个大型表单的时候,表单里有N个select下拉列表,每个下拉select来自于不同的表;

    如果要在程序里用实例化引入这些model类,估计又是N个use引用,而且还需要写查询方法。

    所以铁牛在使用过程中,就思考能否创建动态表模型来应用到我们的开发中。

    代码见下:

    namespace backendclasses;
    //创建动态表模型 
    //在使用调用某些表数据的时候,勿需创建模型既可调用表数据,生成select
    //$select= new SelectMade('bus_department',['id','department'],'sort','department','department');
    //$department=$select->dropdown();
    class SelectMade extends yiidbActiveRecord {
        static $table;
        private $field;
        public $model;
        public $order;
        public $count;
        public $selectId;
        public $extends;
        public $selectName;
        public $itemid;
        //$table String 表名称
        //$field Array 要查找的字段  egg:['id','department']
        //$order String 排序字段
        //$selectName String 下拉列表的名称
        //$selectId String 下拉列表的ID
        //$itemid   Int 自增列序号或主键值
        //$extends 下拉列表的扩展属性 'egg:<select $extends></select>
        public function __construct($table,$field,$order,$selectName,$selectId,$itemid='',$extends='') {
            self::$table=$table;
            $this->field=$field;
            $this->order=$order;
            $this->selectId=$selectId;
            $this->extends=$extends;
            $this->selectName=$selectName;
            $this->itemid=$itemid;
            parent::__construct();
        }
        //定义动态表名词,数据来自于初始化类时
        public static function tableName(){
            return self::$table;
           
        }
        //数据查询
        public function query(){
            //获得相应的下拉的数组
            $this->model=$this->find()
                    ->select($this->field)
                    ->orderBy($this->order)
                    ->asArray()
                    ->all();
           //获得记录的条数,为后续统计服务 ,目前我是预留着,为后续JSON做准备。
            $this->count=$this->find()
                    ->select($this->field)
                    ->orderBy($this->order)
                    ->count();
        }
        //动态生成下拉菜单
        //return String  
        public function dropdown(){
            $this->query();
            $dropdown='<select id="'.$this->selectId.'" name="'.$this->selectName.'" class="easyui-combobox" '.$this->extends.'>';
    
            foreach (array_values($this->model) as $k=>$v){
               $v=  array_values($v);
               $m=($v[0]==$this->itemid)?' selected="selected"':' ';
               $dropdown.=' <option value="'.$v[0].'" '.$m.'>'.$v[1].'</option>';
            }
            $dropdown.='</select>';
            return $dropdown;
        }
        
  • 相关阅读:
    2558: 游起来吧!超妹!
    2554: 巨巨来袭
    2557: 不如来21玩一局?
    tortoisesvn 本项目的忽略项
    【C语言】随机数随机种子
    【leetcode】按奇偶排序数组
    【leetcode】按奇偶排序数组 II
    【leetcode】根据数字二进制下 1 的数目排序
    【leetcode】合并排序的数组
    【leetcode】稀疏数组搜索
  • 原文地址:https://www.cnblogs.com/keleyu/p/4425726.html
Copyright © 2011-2022 走看看