YII2框架動態創建表模型
在YII2中,每個表對應一個model類
在開發過程中,我們在填寫一個大型表單的時候,表單里有N個select下拉列表,每個下拉select來自於不同的表;
如果要在程序里用實例化引入這些model類,估計又是N個use引用,而且還需要寫查詢方法。
所以鐵牛在使用過程中,就思考能否創建動態表模型來應用到我們的開發中。
代碼見下:
namespace backend\classes; //創建動態表模型 //在使用調用某些表數據的時候,勿需創建模型既可調用表數據,生成select //$select= new SelectMade('bus_department',['id','department'],'sort','department','department'); //$department=$select->dropdown(); class SelectMade extends \yii\db\ActiveRecord { 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; }