BaseModel.php 7.7 KB

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