Modelx.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace app\admin\model\cms;
  3. use think\Config;
  4. use think\Db;
  5. use think\Exception;
  6. use think\Model;
  7. class Modelx extends Model
  8. {
  9. // 表名
  10. protected $name = 'cms_model';
  11. // 自动写入时间戳字段
  12. protected $autoWriteTimestamp = 'int';
  13. // 定义时间戳字段名
  14. protected $createTime = 'createtime';
  15. protected $updateTime = 'updatetime';
  16. // 追加属性
  17. protected $append = [
  18. ];
  19. public static function init()
  20. {
  21. self::beforeInsert(function ($row) {
  22. $row['setting'] = '{"contributefields":["image","tags","content"]}';
  23. if (!preg_match("/^([a-z0-9_]+)$/", $row['table'])) {
  24. throw new Exception("表名只支持小写字母、数字、下划线");
  25. }
  26. });
  27. self::afterInsert(function ($row) {
  28. $prefix = Config::get('database.prefix');
  29. $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']}'";
  30. Db::execute($sql);
  31. });
  32. //存在栏目无法删除
  33. self::beforeDelete(function ($row) {
  34. $exist = Channel::where('model_id', $row['id'])->find();
  35. if ($exist) {
  36. throw new Exception("模型下存在栏目,无法进行删除");
  37. }
  38. });
  39. //删除模型后删除对应的表字段
  40. self::afterDelete(function ($row) {
  41. Db::name("cms_fields")->where(['source' => 'model', 'source_id' => $row['id']])->delete();
  42. });
  43. }
  44. public function getFieldsAttr($value, $data)
  45. {
  46. return is_array($value) ? $value : ($value ? explode(',', $value) : []);
  47. }
  48. public function getSettingAttr($value, $data)
  49. {
  50. return is_array($value) ? $value : (array)json_decode($data['setting'], true);
  51. }
  52. public function setSettingAttr($value)
  53. {
  54. return is_array($value) ? json_encode($value) : $value;
  55. }
  56. }