FieldService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. <?php
  2. namespace app\admin\service\sys_manage;
  3. use app\common\Util;
  4. use app\model\SysField;
  5. use Illuminate\Database\Schema\Blueprint;
  6. use Illuminate\Support\Facades\Schema;
  7. use support\Db;
  8. use support\Request;
  9. class FieldService
  10. {
  11. /**
  12. * @Desc 字段列表
  13. * @Author Gorden
  14. * @Date 2024/2/22 14:49
  15. *
  16. * @param $page
  17. * @param $limit
  18. * @param $keywords
  19. * @return \support\Response
  20. */
  21. public static function fieldList(Request $request)
  22. {
  23. $page = $request->get('page', 1);
  24. $pageSize = $request->get('pageSize', 10);
  25. $fieldName = $request->get('field_name', '');
  26. $tableName = $request->get('table_name', '');
  27. $fieldCategory = $request->get('field_category', '');
  28. $rows = SysField::select('*')
  29. ->when($fieldName != '', function ($query) use ($fieldName) {
  30. $query->where('field_name', 'like', '%' . $fieldName . '%');
  31. })->when($tableName != '', function ($query) use ($tableName) {
  32. $query->where('field_table', 'like', '%' . $tableName . '%');
  33. })->when($fieldCategory != '', function ($query) use ($fieldCategory) {
  34. $query->where('field_category', $fieldCategory);
  35. })->orderBy('field_addtimes', 'DESC')
  36. ->forPage($page, $pageSize)
  37. ->get()
  38. ->toArray();
  39. $total = SysField::when($fieldName != '', function ($query) use ($fieldName) {
  40. $query->where('field_name', 'like', '%' . $fieldName . '%');
  41. })->when($tableName != '', function ($query) use ($tableName) {
  42. $query->where('field_table', 'like', '%' . $tableName . '%');
  43. })->count();
  44. foreach ($rows as &$row) {
  45. $row['field_refer_json'] = json_decode($row['field_refer_json']);
  46. }
  47. return json_success('', compact('rows', 'page', 'pageSize', 'total'));
  48. }
  49. /**
  50. * @Desc 字段详情
  51. * @Author Gorden
  52. * @Date 2024/2/22 14:55
  53. *
  54. * @param $id
  55. * @return \support\Response
  56. */
  57. public static function fieldInfo($id)
  58. {
  59. $field = SysField::where('field_id', $id)->first();
  60. if (!$field) {
  61. return json_fail('字段不存在');
  62. }
  63. return json_success('', $field->toArray());
  64. }
  65. /**
  66. * @Desc 新建字段
  67. * @Author Gorden
  68. * @Date 2024/2/22 14:31
  69. *
  70. * @param $params
  71. * @return \support\Response
  72. */
  73. public static function addField($params)
  74. {
  75. if (!empty($params['field_refer_json']['key'])) {
  76. $params['field_refer_json']['val'] = $params['field_refer_json']['key'];
  77. }
  78. Db::beginTransaction();
  79. try {
  80. $data = [
  81. 'field_status' => $params['field_status'],
  82. 'field_category' => $params['field_category'],
  83. 'field_name' => $params['field_name'],
  84. 'field_table' => $params['field_table'],
  85. 'field_column_key' => $params['field_column_key'] ?? '',
  86. 'field_column_datatype' => $params['field_column_datatype'] ?? '',
  87. 'field_column_default' => $params['field_column_default'] ?? '',
  88. 'field_form_key' => $params['field_form_key'] ?? '',
  89. 'field_form_type' => $params['field_form_type'] ?? '',
  90. 'field_form_default' => $params['field_form_default'] ?? '',
  91. 'field_refer_json' => !empty($params['field_refer_json']) ? json_encode($params['field_refer_json']) : [],
  92. 'field_remark' => $params['field_remark'] ?? '',
  93. 'field_extend_json' => !empty($params['field_extend_json']) ? $params['field_extend_json'] : [],
  94. 'field_addtimes' => time()
  95. ];
  96. // 入库
  97. SysField::insert($data);
  98. if (!empty($params['field_table'])) {
  99. // 字段设置
  100. $column = [
  101. 'type' => self::$column[$params['field_column_datatype']],
  102. 'field' => $params['field_column_key'],
  103. 'primary_key' => false,
  104. 'nullable' => true,
  105. 'default' => $params['field_column_default'],
  106. 'auto_increment' => false,
  107. 'comment' => $params['field_name']
  108. ];
  109. $defaultLength = Util::fieldDefaultLength();
  110. if (isset($defaultLength[$column['type']])) {
  111. $column['length'] = $defaultLength[$column['type']];
  112. }
  113. // 写入字段
  114. Util::schema()->table($params['field_table'], function (Blueprint $table) use ($column) {
  115. self::createColumn($table, $column);
  116. });
  117. }
  118. Db::commit();
  119. } catch (\Exception $e) {
  120. Db::rollBack();
  121. return json_fail('创建字段失败');
  122. }
  123. return json_success('创建字段成功');
  124. }
  125. /**
  126. * @Desc 修改字段
  127. * @Author Gorden
  128. * @Date 2024/2/22 14:40
  129. *
  130. * @param $id
  131. * @param $params
  132. * @return \support\Response
  133. */
  134. public static function updateField($id, $params)
  135. {
  136. Db::beginTransaction();
  137. try {
  138. $field = SysField::where('field_id', $id)->first();
  139. $data = [
  140. 'field_category' => $params['field_category'],
  141. 'field_name' => $params['field_name'],
  142. 'field_table' => $params['field_table'],
  143. 'field_column_key' => $params['field_column_key'],
  144. 'field_column_datatype' => $params['field_column_datatype'],
  145. 'field_column_default' => $params['field_column_default'],
  146. 'field_form_key' => $params['field_form_key'],
  147. 'field_form_type' => $params['field_form_type'],
  148. 'field_form_default' => $params['field_form_default'],
  149. 'field_refer_json' => !empty($params['field_refer_json']) ? json_encode($params['field_refer_json']) : '[]',
  150. 'field_remark' => $params['field_remark'],
  151. // 'field_extend_json' => !empty($params['field_extend_json']) ? $params['field_extend_json'] : '[]'
  152. ];
  153. // 更新
  154. SysField::where('field_id', $id)->update($data);
  155. if (!empty($params['field_table'])) {
  156. // 字段设置
  157. $column = [
  158. 'type' => self::$column[$params['field_column_datatype']],
  159. 'field' => $params['field_column_key'],
  160. 'old_field' => $field->field_column_key,
  161. 'primary_key' => false,
  162. 'nullable' => true,
  163. 'default' => $params['field_column_default'],
  164. 'auto_increment' => false,
  165. 'comment' => $params['field_name']
  166. ];
  167. // 设置字段长度
  168. $defaultLength = Util::fieldDefaultLength();
  169. if (isset($defaultLength[$column['type']])) {
  170. $column['length'] = $defaultLength[$column['type']];
  171. }
  172. // 表变动
  173. if ($field->field_table != $params['field_table']) {
  174. if (!empty($field->field_table)) {
  175. // 删原表字段
  176. Util::db()->statement("ALTER TABLE " . getenv('DB_PREFIX') . $field->field_table . " DROP COLUMN `$field->field_column_key`");
  177. }
  178. // 在新表创建
  179. Util::schema()->table($params['field_table'], function (Blueprint $table) use ($column) {
  180. self::createColumn($table, $column);
  181. });
  182. } else {
  183. // 表没变,改就行
  184. self::modifyColumn($params['field_table'], $column);
  185. }
  186. }
  187. Db::commit();
  188. } catch (\Exception $e) {
  189. Db::rollBack();
  190. dump($e->getMessage());
  191. return json_fail('修改字段失败');
  192. }
  193. return json_success('修改字段成功');
  194. }
  195. /**
  196. * @Desc 修改字段状态
  197. * @Author Gorden
  198. * @Date 2024/2/22 15:06
  199. *
  200. * @param $id
  201. * @param $params
  202. * @return \support\Response
  203. */
  204. public static function updateStatus($id, $params)
  205. {
  206. try {
  207. SysField::where('field_id', $id)->update(['field_status' => $params['field_status']]);
  208. } catch (\Exception $e) {
  209. return json_fail('字段状态修改失败');
  210. }
  211. return json_success('字段状态修改成功');
  212. }
  213. /**
  214. * @Desc 删除字段
  215. * @Author Gorden
  216. * @Date 2024/2/22 15:08
  217. *
  218. * @param $id
  219. * @return \support\Response
  220. */
  221. public static function delField($ids)
  222. {
  223. Db::beginTransaction();
  224. try {
  225. if (!is_array($ids)) {
  226. $ids = [$ids];
  227. }
  228. foreach ($ids as $id) {
  229. $field = SysField::where('field_id', $id)->first();
  230. // 删除表记录
  231. $field->delete();
  232. // 删除表字段
  233. Util::db()->statement("ALTER TABLE " . getenv('DB_PREFIX') . $field->field_table . " DROP COLUMN `$field->field_column_key`");
  234. }
  235. // 提交事务
  236. Db::commit();
  237. } catch (\Exception $e) {
  238. // 回滚
  239. Db::rollBack();
  240. return json_fail('字段删除失败');
  241. }
  242. return json_success('字段删除成功');
  243. }
  244. public static function checkTableExist($table)
  245. {
  246. if (empty($table)) {
  247. return true;
  248. }
  249. try {
  250. // $table = $table;
  251. $desc = (new SysField)->getConnection()->select("desc `$table`");
  252. if ($desc) {
  253. return true;
  254. }
  255. } catch (\Exception $e) {
  256. return false;
  257. }
  258. }
  259. /**
  260. * @Desc 验证表字段是否存在
  261. * @Author Gorden
  262. * @Date 2024/2/23 11:49
  263. *
  264. * @param $table
  265. * @param $field
  266. * @return bool
  267. */
  268. public static function checkFieldExist($table, $field)
  269. {
  270. if (empty($table)) {
  271. return true;
  272. }
  273. return SysField::where('field_table', $table)
  274. ->where('field_column_key', $field)
  275. ->exists();
  276. }
  277. /**
  278. * 创建字段
  279. * @param $column
  280. * @param Blueprint $table
  281. * @return mixed
  282. * @throws \Exception
  283. */
  284. public static function createColumn(Blueprint $table, $column)
  285. {
  286. $method = $column['type'];
  287. $args = [$column['field']];
  288. $type_method_map = Util::methodControlMap();
  289. if (!isset($column['type'])) {
  290. throw new \Exception("请为{$column['field']}选择类型");
  291. }
  292. if (!isset($type_method_map[$column['type']])) {
  293. throw new \Exception("不支持的类型{$column['type']}");
  294. }
  295. if (stripos($method, 'int') !== false) {
  296. // auto_increment 会自动成为主键
  297. if ($column['auto_increment']) {
  298. $column['nullable'] = false;
  299. $column['default'] = null;
  300. $args[] = true;
  301. }
  302. } elseif (in_array($method, ['string', 'char']) || stripos($method, 'time') !== false) {
  303. if ($column['length']) {
  304. $args[] = $column['length'];
  305. }
  306. } elseif ($method === 'enum') {
  307. $args[] = array_map('trim', explode(',', $column['length']));
  308. } elseif (in_array($method, ['float', 'decimal', 'double'])) {
  309. if ($column['length']) {
  310. $args = array_merge($args, array_map('trim', explode(',', $column['length'])));
  311. }
  312. } else {
  313. $column['auto_increment'] = false;
  314. }
  315. $column_def = call_user_func_array([$table, $method], $args);
  316. if (!empty($column['comment'])) {
  317. $column_def = $column_def->comment($column['comment']);
  318. }
  319. if (!$column['auto_increment'] && $column['primary_key']) {
  320. $column_def = $column_def->primary(true);
  321. }
  322. if ($column['auto_increment'] && !$column['primary_key']) {
  323. $column_def = $column_def->primary(false);
  324. }
  325. $column_def = $column_def->nullable($column['nullable']);
  326. if ($column['primary_key']) {
  327. $column_def = $column_def->nullable(false);
  328. }
  329. if ($method != 'text' && $column['default'] !== null) {
  330. $column_def->default($column['default']);
  331. }
  332. return $column_def;
  333. }
  334. /**
  335. * 更改字段
  336. * @param $column
  337. * @param $table
  338. * @return mixed
  339. * @throws \Exception
  340. */
  341. protected static function modifyColumn($table, $column)
  342. {
  343. $method = $column['type'];
  344. $field = $column['field'];
  345. $old_field = $column['old_field'] ?? null;
  346. $nullable = $column['nullable'];
  347. $default = $column['default'] !== null ? Util::pdoQuote($column['default']) : null;
  348. $comment = Util::pdoQuote($column['comment']);
  349. $auto_increment = $column['auto_increment'];
  350. $length = (int)$column['length'];
  351. if ($column['primary_key']) {
  352. $default = null;
  353. }
  354. if ($old_field && $old_field !== $field) {
  355. $sql = "ALTER TABLE `$table` CHANGE COLUMN `$old_field` `$field` ";
  356. } else {
  357. $sql = "ALTER TABLE `$table` MODIFY `$field` ";
  358. }
  359. if (stripos($method, 'integer') !== false) {
  360. $type = str_ireplace('integer', 'int', $method);
  361. if (stripos($method, 'unsigned') !== false) {
  362. $type = str_ireplace('unsigned', '', $type);
  363. $sql .= "$type ";
  364. $sql .= 'unsigned ';
  365. } else {
  366. $sql .= "$type ";
  367. }
  368. if ($auto_increment) {
  369. $column['nullable'] = false;
  370. $column['default'] = null;
  371. $sql .= 'AUTO_INCREMENT ';
  372. }
  373. } else {
  374. switch ($method) {
  375. case 'string':
  376. $length = $length ?: 255;
  377. $sql .= "varchar($length) ";
  378. break;
  379. case 'char':
  380. case 'time':
  381. $sql .= $length ? "$method($length) " : "$method ";
  382. break;
  383. case 'enum':
  384. $args = array_map('trim', explode(',', (string)$column['length']));
  385. foreach ($args as $key => $value) {
  386. $args[$key] = Util::pdoQuote($value);
  387. }
  388. $sql .= 'enum(' . implode(',', $args) . ') ';
  389. break;
  390. case 'double':
  391. case 'float':
  392. case 'decimal':
  393. if (trim($column['length'])) {
  394. $args = array_map('intval', explode(',', $column['length']));
  395. $args[1] = $args[1] ?? $args[0];
  396. $sql .= "$method($args[0], $args[1]) ";
  397. break;
  398. }
  399. $sql .= "$method ";
  400. break;
  401. default :
  402. $sql .= "$method ";
  403. }
  404. }
  405. if (!$nullable) {
  406. $sql .= "NOT NULL ";
  407. }
  408. if ($method != 'text' && $default !== null) {
  409. $sql .= "DEFAULT $default ";
  410. }
  411. if ($comment !== null) {
  412. $sql .= "COMMENT $comment ";
  413. }
  414. echo "$sql\n";
  415. Util::db()->statement($sql);
  416. }
  417. public static $column = [
  418. 'VARCHAR' => 'string',
  419. 'DATETIME' => 'dateTime',
  420. 'INT' => 'integer',
  421. 'DECIMAL' => 'decimal'
  422. ];
  423. }