Field.php 2.04 KB
<?php

namespace addons\antis\model;

use think\Exception;
use think\Model;
use think\Session;

/**
 * 配置模型
 */
class Field extends Model
{
    // 表名,不含前缀
    protected $name = 'qingdong_field';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;
    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;


    //获取字段
    public static function getField($name,$type=null)
    {
        $where = [];
        if($type){
            $where['type'] = $type;
        }
        $data=self::where($where)->where(['name' => $name])->value('data');
        if(empty($data)){
            return [];
        }
        return json_decode($data,true);
    }


    //修改字段
    public function fields()
    {
        return $this->hasOne(self::class, 'type', 'type')->field('type,data');
    }

    //设置form 表单选项
    public function setFormField($type, $data)
    {
        $insertAll = [];
        foreach ($data as $v) {
            if ($v['component'] == 'select') {
                $insertAll[] = [
                    'type' => $type,
                    'name' => $v['config']['label'],
                    'data' => json_encode($this->getDataFields($v['config']['content']), JSON_UNESCAPED_UNICODE)
                ];
            }
        }
        $model = new self;

        $model->where(['type' => $type])->delete();
        if(empty($insertAll)){
            return true;
        }
        if ($model->insertAll($insertAll) == false) {
            throw new Exception('新增表单失败');
        }
        return true;
    }

    //循环获取data里面的字段
    private function getDataFields($data, $fields = [])
    {
        foreach ($data as $v) {
            $fields[] = $v['label'];
            if (isset($v['children']) && $v['children']) {
                $fields = self::getDataFields($data['children'], $fields);
            }
        }

        return $fields;
    }


}