BaseModel.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | saiadmin [ saiadmin快速开发框架 ]
  4. // +----------------------------------------------------------------------
  5. // | Author: sai <1430792918@qq.com>
  6. // +----------------------------------------------------------------------
  7. namespace plugin\saiadmin\basic\think;
  8. use support\think\Model;
  9. use think\model\concern\SoftDelete;
  10. use plugin\saiadmin\basic\contracts\ModelInterface;
  11. /**
  12. * ThinkORM 模型基类
  13. */
  14. class BaseModel extends Model implements ModelInterface
  15. {
  16. use SoftDelete;
  17. /**
  18. * 删除时间字段
  19. * @var string
  20. */
  21. protected $deleteTime = 'delete_time';
  22. /**
  23. * 创建时间字段
  24. * @var string
  25. */
  26. protected $createTime = 'create_time';
  27. /**
  28. * 更新时间字段
  29. * @var string
  30. */
  31. protected $updateTime = 'update_time';
  32. /**
  33. * 隐藏字段
  34. * @var array
  35. */
  36. protected $hidden = ['delete_time'];
  37. /**
  38. * 只读字段
  39. * @var array
  40. */
  41. protected $readonly = ['created_by', 'create_time'];
  42. /**
  43. * 获取表名
  44. * @return string
  45. */
  46. public function getTableName(): string
  47. {
  48. return $this->getTable();
  49. }
  50. /**
  51. * 获取主键名
  52. * @return string
  53. */
  54. public function getPrimaryKeyName(): string
  55. {
  56. return $this->getPk();
  57. }
  58. /**
  59. * 添加时间范围搜索
  60. * @param $query
  61. * @param $value
  62. */
  63. public function searchCreateTimeAttr($query, $value)
  64. {
  65. if (is_array($value)) {
  66. $query->whereBetween('create_time', $value);
  67. } else {
  68. $query->where('create_time', '=', $value);
  69. }
  70. }
  71. /**
  72. * 更新时间范围搜索
  73. * @param mixed $query
  74. * @param mixed $value
  75. */
  76. public function searchUpdateTimeAttr($query, $value)
  77. {
  78. if (is_array($value)) {
  79. $query->whereBetween('update_time', $value);
  80. } else {
  81. $query->where('update_time', '=', $value);
  82. }
  83. }
  84. /**
  85. * 新增前事件
  86. * @param Model $model
  87. * @return void
  88. */
  89. public static function onBeforeInsert($model): void
  90. {
  91. $info = getCurrentInfo();
  92. $info && $model->setAttr('created_by', $info['id']);
  93. }
  94. /**
  95. * 写入前事件
  96. * @param Model $model
  97. * @return void
  98. */
  99. public static function onBeforeWrite($model): void
  100. {
  101. $info = getCurrentInfo();
  102. $info && $model->setAttr('updated_by', $info['id']);
  103. }
  104. }