You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
3.3 KiB

<?php
namespace App\Models;
use App\Exceptions\ErrorException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class CustomFormField extends SoftDeletesModel
{
public $casts = [
'validation' => 'json',
'select_item' => 'json'
];
// 白名单字段,每个表都会有
public $whiteList = ['id', 'admin_id', 'department_id', 'created_at', 'updated_at', 'deleted_at'];
public static $validationRules = [
'required' => '必填',
'unique' => '唯一',
'date' => '日期',
'email' => '邮箱',
'integer' => '整数',
'numeric' => '数字',
'mobile' => '手机号',
'idcard' => '身份证号',
];
/**
* 输入字段检测
* @param $all
*/
public function checkFields($all)
{
$model = new CustomFormField();
if (isset($all['id'])) {
// 判断不能重名
$check = $model->where('custom_form_id', $all['custom_form_id'])->where('field', $all['field'])->where('id', '!=', $all['id'])->first();
if ($check) throw new ErrorException('字段名重复');
} else {
// 判断不能重名
$check = $model->where('custom_form_id', $all['custom_form_id'])->where('field', $all['field'])->first();
if ($check) throw new ErrorException('字段名重复');
}
return $all;
}
/**
* 获取原始数据表的表结构和数据类型
*/
public function getRowTableFieldsByType($tableName, $showAll = false, $cache = true)
{
if ($cache) {
return Cache::remember('row_table_fields_by_type_' . $tableName, CustomForm::$cache_ttl, function () use ($tableName, $showAll) {
return $this->rowTableFieldsByType($tableName, $showAll);
});
} else {
return $this->rowTableFieldsByType($tableName, $showAll);
}
}
/**
* 获取原始数据表的表结构和备注
*/
public function getRowTableFieldsByComment($tableName, $except = [], $symbol = '-')
{
$columns = DB::select(DB::raw("SHOW FULL COLUMNS FROM {$tableName}"));
// 转数组
$columns = json_decode(json_encode($columns), true);
$array = array_column($columns, 'Comment', 'Field');
$list = [];
foreach ($array as $key => $item) {
// 去掉排除的数据
if (in_array($key, $except)) {
continue;
}
// 根据分隔符取前面的字段名
$item = explode($symbol, $item);
$list[$key] = $item[0];
}
return $list;
}
/**
* 获取原始数据表的表结构和数据类型
*/
public function rowTableFieldsByType($tableName, $showAll = false)
{
$rowColumn = Schema::getColumnListing($tableName);
// 遍历表列信息
$list = [];
foreach ($rowColumn as $column) {
// 获取每个列的类型
$columnType = Schema::getColumnType($tableName, $column);
if (!$showAll && in_array($column, $this->whiteList)) {
continue;
}
$list = array_merge($list, [$column => $columnType]);
}
return $list;
}
}