BaseModel.php 7.7 KB

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