BaseModel.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace cores;
  13. use think\Model;
  14. use think\db\Query;
  15. use think\helper\Str;
  16. use app\common\library\helper;
  17. use cores\traits\ErrorTrait;
  18. /**
  19. * 模型基类
  20. * Class BaseModel
  21. * @package app\common\model
  22. */
  23. abstract class BaseModel extends Model
  24. {
  25. use ErrorTrait;
  26. // 当前访问的商城ID
  27. public static ?int $storeId = null;
  28. // 定义表名
  29. protected $name;
  30. // 模型别名
  31. protected string $alias = '';
  32. // 定义全局的查询范围
  33. protected $globalScope = ['store_id'];
  34. // 是否允许全局查询store_id
  35. protected bool $isGlobalScopeStoreId = true;
  36. /**
  37. * 模型基类初始化
  38. */
  39. public static function init()
  40. {
  41. parent::init();
  42. // 绑定store_id
  43. self::getStoreId();
  44. }
  45. /**
  46. * 获取当前操作的商城ID
  47. * @return int|null
  48. */
  49. private static function getStoreId(): ?int
  50. {
  51. if (empty(self::$storeId) && \in_array(\app_name(), ['store', 'api'])) {
  52. self::$storeId = \getStoreId();
  53. }
  54. return self::$storeId;
  55. }
  56. /**
  57. * 获取当前调用来源的应用名称
  58. * 例如:admin, api, store
  59. * @return string
  60. */
  61. protected final static function getCalledModule(): string
  62. {
  63. if (preg_match('/app\\\(\w+)/', get_called_class(), $class)) {
  64. return $class[1];
  65. }
  66. return 'common';
  67. }
  68. /**
  69. * 查找单条记录
  70. * @param mixed $data 查询条件
  71. * @param array $with 关联查询
  72. * @return array|static|null
  73. */
  74. public static function get($data, array $with = [])
  75. {
  76. try {
  77. $query = (new static)->with($with);
  78. return is_array($data) ? $query->where($data)->find() : $query->find((int)$data);
  79. } catch (\Exception $e) {
  80. return null;
  81. }
  82. }
  83. /**
  84. * 获取当前表名称 (不含前缀)
  85. * @return string
  86. */
  87. public static final function getTableName(): string
  88. {
  89. $model = new static;
  90. return Str::snake($model->name);
  91. }
  92. /**
  93. * 定义全局的查询范围
  94. * @param Query $query
  95. */
  96. public function scopeStore_id(Query $query)
  97. {
  98. if (!$this->isGlobalScopeStoreId) return;
  99. $storeId = self::getStoreId();
  100. $storeId > 0 && $query->where($query->getTable() . '.store_id', $storeId);
  101. }
  102. /**
  103. * 设置默认的检索数据
  104. * @param array $query
  105. * @param array $default
  106. * @return array
  107. */
  108. public function setQueryDefaultValue(array $query, array $default = []): array
  109. {
  110. return helper::setQueryDefaultValue($query, $default);
  111. }
  112. /**
  113. * 设置基础查询条件(用于简化基础alias和field)
  114. * @param string $alias
  115. * @param array $join
  116. * @return $this
  117. */
  118. public function setBaseQuery(string $alias = '', array $join = [])
  119. {
  120. // 设置别名
  121. $aliasValue = $alias ?: $this->alias;
  122. $query = $this->alias($aliasValue)->field("{$aliasValue}.*");
  123. // join条件
  124. if (!empty($join)) : foreach ($join as $item):
  125. $query->join($item[0], "{$item[0]}.{$item[1]}={$aliasValue}." . ($item[2] ?? $item[1]));
  126. endforeach; endif;
  127. return $query;
  128. }
  129. /**
  130. * 批量更新多条数据
  131. * @param iterable $dataSet [0 => ['data'=>[], 'where'=>[]]]
  132. * @return array|false
  133. */
  134. public function updateAll(iterable $dataSet)
  135. {
  136. if (empty($dataSet)) {
  137. return false;
  138. }
  139. return $this->transaction(function () use ($dataSet) {
  140. $result = [];
  141. foreach ($dataSet as $key => $item) {
  142. $result[$key] = self::updateBase($item['data'], $item['where']);
  143. }
  144. return $result;
  145. });
  146. }
  147. /**
  148. * 批量新增数据
  149. * @param iterable $dataSet [0 => ['id'=>10001, 'name'=>'wang']]
  150. * @return array|false
  151. */
  152. public function addAll(iterable $dataSet)
  153. {
  154. if (empty($dataSet)) {
  155. return false;
  156. }
  157. return $this->transaction(function () use ($dataSet) {
  158. $result = [];
  159. foreach ($dataSet as $key => $item) {
  160. $result[$key] = self::create($item, $this->field);
  161. }
  162. return $result;
  163. });
  164. }
  165. /**
  166. * 删除记录
  167. * @param array $where
  168. * 方式1: ['goods_id' => $goodsId]
  169. * 方式2: [
  170. * ['store_user_id', '=', $storeUserId],
  171. * ['role_id', 'in', $deleteRoleIds]
  172. * ]
  173. * @return bool|int 这里实际返回的是数量int
  174. */
  175. public static function deleteAll(array $where)
  176. {
  177. return (new static)->where($where)->delete();
  178. }
  179. /**
  180. * 字段值增长
  181. * @param array|int|bool $where
  182. * @param string $field
  183. * @param float $step
  184. * @return mixed
  185. */
  186. protected function setInc($where, string $field, float $step = 1)
  187. {
  188. if (is_numeric($where)) {
  189. $where = [$this->getPk() => (int)$where];
  190. }
  191. return $this->where($where)->inc($field, $step)->update();
  192. }
  193. /**
  194. * 字段值消减
  195. * @param array|int|bool $where
  196. * @param string $field
  197. * @param float $step
  198. * @return mixed
  199. */
  200. protected function setDec($where, string $field, float $step = 1)
  201. {
  202. if (is_numeric($where)) {
  203. $where = [$this->getPk() => (int)$where];
  204. }
  205. return $this->where($where)->dec($field, $step)->update();
  206. }
  207. /**
  208. * 实例化新查询对象
  209. * @return \think\db\BaseQuery
  210. */
  211. protected function getNewQuery(): \think\db\BaseQuery
  212. {
  213. return $this->db();
  214. }
  215. /**
  216. * 新增hidden属性
  217. * @param array $hidden
  218. * @return $this
  219. */
  220. protected function addHidden(array $hidden): BaseModel
  221. {
  222. $this->hidden = array_merge($this->hidden, $hidden);
  223. return $this;
  224. }
  225. /**
  226. * 生成字段列表(字段加上$alias别名)
  227. * @param string $alias 别名
  228. * @param array $withoutFields 排除的字段
  229. * @return array
  230. */
  231. protected function getAliasFields(string $alias, array $withoutFields = []): array
  232. {
  233. $fields = array_diff($this->getTableFields(), $withoutFields);
  234. foreach ($fields as &$field) {
  235. $field = "$alias.$field";
  236. }
  237. return $fields;
  238. }
  239. /**
  240. * 更新数据[批量]
  241. * @param array $data 更新的数据内容
  242. * @param array|int $where 更新条件
  243. * @param array $allowField 允许的字段
  244. * @return bool
  245. */
  246. public static function updateBase(array $data, $where, array $allowField = []): bool
  247. {
  248. $model = new static;
  249. if (!empty($allowField)) {
  250. $model->allowField($allowField);
  251. }
  252. if (is_numeric($where)) {
  253. $where = [$model->getPk() => $where];
  254. }
  255. return $model->mySetUpdateWhere($where)->exists(true)->save($data);
  256. }
  257. /**
  258. * 设置模型的更新条件
  259. * @access protected
  260. * @param mixed $where 更新条件
  261. * @return static
  262. */
  263. public function mySetUpdateWhere($where): BaseModel
  264. {
  265. $this->setUpdateWhere($where);
  266. return $this;
  267. }
  268. /**
  269. * 获取隐藏的属性
  270. * @param array $hidden 合并的隐藏属性
  271. * @return array
  272. */
  273. public static function getHidden(array $hidden = []): array
  274. {
  275. return array_merge((new static)->hidden, $hidden);
  276. }
  277. }