Modelx.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace app\admin\model\cms;
  3. use think\Config;
  4. use think\Db;
  5. use think\Exception;
  6. use think\exception\PDOException;
  7. use think\Model;
  8. class Modelx extends Model
  9. {
  10. // 表名
  11. protected $name = 'cms_model';
  12. // 自动写入时间戳字段
  13. protected $autoWriteTimestamp = 'int';
  14. // 定义时间戳字段名
  15. protected $createTime = 'createtime';
  16. protected $updateTime = 'updatetime';
  17. // 追加属性
  18. protected $append = [
  19. ];
  20. public static function init()
  21. {
  22. self::beforeInsert(function ($row) {
  23. $setting = [
  24. 'contributefields' => Fields::getContributeFields(),
  25. 'publishfields' => Fields::getPublishFields(),
  26. ];
  27. $row['setting'] = json_encode($setting);
  28. if (!preg_match("/^([a-z0-9_]+)$/", $row['table'])) {
  29. throw new Exception("表名只支持小写字母、数字、下划线");
  30. }
  31. $exist = Modelx::where('table', $row['table'])->find();
  32. if ($exist) {
  33. throw new Exception("已经存在相同表名的模型");
  34. }
  35. $info = null;
  36. try {
  37. $info = Db::name($row['table'])->getTableInfo();
  38. } catch (\Exception $e) {
  39. }
  40. if ($info) {
  41. throw new Exception("数据表已经存在");
  42. }
  43. });
  44. self::afterInsert(function ($row) {
  45. $prefix = Config::get('database.prefix');
  46. $sql = "CREATE TABLE `{$prefix}{$row['table']}` (`id` int(10) NOT NULL,`content` longtext NOT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='{$row['name']}'";
  47. try {
  48. Db::execute($sql);
  49. } catch (\Exception $e) {
  50. throw new Exception("发生错误:" . $e->getMessage());
  51. }
  52. });
  53. //存在栏目无法删除
  54. self::beforeDelete(function ($row) {
  55. $exist = Channel::where('model_id', $row['id'])->find();
  56. if ($exist) {
  57. throw new Exception("模型下存在栏目,无法进行删除");
  58. }
  59. });
  60. //删除模型后删除对应的表字段
  61. self::afterDelete(function ($row) {
  62. Db::name("cms_fields")->where(['source' => 'model', 'source_id' => $row['id']])->delete();
  63. });
  64. }
  65. public function getFieldsAttr($value, $data)
  66. {
  67. return is_array($value) ? $value : ($value ? explode(',', $value) : []);
  68. }
  69. public function getSettingAttr($value, $data)
  70. {
  71. return is_array($value) ? $value : (array)json_decode($data['setting'], true);
  72. }
  73. public function setSettingAttr($value)
  74. {
  75. return is_array($value) ? json_encode($value) : $value;
  76. }
  77. }