BaseModel.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 app\common\model;
  13. use think\Model;
  14. use think\db\Query;
  15. /**
  16. * 模型基类
  17. * Class BaseModel
  18. * @package app\common\model
  19. */
  20. 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 = false;
  32. // 错误信息
  33. protected $error = '';
  34. public static $oss_domain;
  35. /**
  36. * 模型基类初始化
  37. */
  38. public static function init()
  39. {
  40. parent::init();
  41. // 绑定store_id
  42. self::getStoreId();
  43. }
  44. /**
  45. * 查找单条记录
  46. * @param $data
  47. * @param array $with
  48. * @return array|static|null
  49. */
  50. public static function get($data, $with = [])
  51. {
  52. try {
  53. $query = (new static)->with($with);
  54. return is_array($data) ? $query->where($data)->find() : $query->find((int)$data);
  55. } catch (\Exception $e) {
  56. return false;
  57. }
  58. }
  59. /**
  60. * 定义全局的查询范围
  61. * @param Query $query
  62. * @return bool
  63. */
  64. public function scopeStore_id(Query $query)
  65. {
  66. if (!$this->isGlobalScopeStoreId) return false;
  67. $storeId = self::getStoreId();
  68. $storeId > 0 && $query->where($query->getTable() . '.store_id', $storeId);
  69. return true;
  70. }
  71. /**
  72. * 获取当前操作的商城ID
  73. * @return int|null
  74. */
  75. private static function getStoreId()
  76. {
  77. if (empty(self::$storeId) && in_array(app_name(), ['store', 'api'])) {
  78. self::$storeId = getStoreId();
  79. }
  80. return self::$storeId;
  81. }
  82. /**
  83. * 获取当前调用来源的应用名称
  84. * 例如:admin, api, store, task
  85. * @return string|bool
  86. */
  87. protected static function getCalledModule()
  88. {
  89. if (preg_match('/app\\\(\w+)/', get_called_class(), $class)) {
  90. return $class[1];
  91. }
  92. return 'common';
  93. }
  94. /**
  95. * 设置默认的检索数据
  96. * @param array $query
  97. * @param array $default
  98. * @return array
  99. */
  100. protected function setQueryDefaultValue(array $query, array $default = [])
  101. {
  102. $data = array_merge($default, $query);
  103. foreach ($query as $field => $value) {
  104. // 不存在默认值跳出循环
  105. if (!isset($default[$field])) continue;
  106. // 如果传参为空, 设置默认值
  107. if (empty($value) && $value !== '0') {
  108. $data[$field] = $default[$field];
  109. }
  110. }
  111. return $data;
  112. }
  113. /**
  114. * 设置基础查询条件(用于简化基础alias和field)
  115. * @test 2019-4-25
  116. * @param string $alias
  117. * @param array $join
  118. * @return BaseModel
  119. */
  120. public function setBaseQuery($alias = '', $join = [])
  121. {
  122. // 设置别名
  123. $aliasValue = $alias ?: $this->alias;
  124. $query = $this->alias($aliasValue)->field("{$aliasValue}.*");
  125. // join条件
  126. if (!empty($join)) : foreach ($join as $item):
  127. $query->join($item[0], "{$item[0]}.{$item[1]}={$aliasValue}."
  128. . (isset($item[2]) ? $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 int
  197. */
  198. public static function deleteAll(array $where)
  199. {
  200. return (new static)->where($where)->delete();
  201. }
  202. /**
  203. * 返回错误信息
  204. * @return string
  205. */
  206. public function getError()
  207. {
  208. return empty($this->error) ? false : $this->error;
  209. }
  210. /**
  211. * 字段值增长
  212. * @param array|int|bool $where
  213. * @param string $field
  214. * @param float $step
  215. * @return mixed
  216. */
  217. protected function setInc($where, string $field, float $step = 1)
  218. {
  219. if (is_numeric($where)) {
  220. $where = [$this->getPk() => (int)$where];
  221. }
  222. return $this->where($where)->inc($field, $step)->update();
  223. }
  224. /**
  225. * 字段值消减
  226. * @param array|int|bool $where
  227. * @param string $field
  228. * @param float $step
  229. * @return mixed
  230. */
  231. protected function setDec($where, string $field, float $step = 1)
  232. {
  233. if (is_numeric($where)) {
  234. $where = [$this->getPk() => (int)$where];
  235. }
  236. return $this->where($where)->dec($field, $step)->update();
  237. }
  238. /**
  239. * 实例化新查询对象
  240. * @return \think\db\BaseQuery
  241. */
  242. protected function getNewQuery()
  243. {
  244. return $this->db();
  245. }
  246. /**
  247. * 新增hidden属性
  248. * @param array $hidden
  249. * @return $this
  250. */
  251. protected function addHidden(array $hidden)
  252. {
  253. $this->hidden = array_merge($this->hidden, $hidden);
  254. return $this;
  255. }
  256. /**
  257. * 生成字段列表(字段加上$alias别名)
  258. * @param string $alias 别名
  259. * @param array $withoutFields 排除的字段
  260. * @return array
  261. */
  262. protected function getAliasFields(string $alias, $withoutFields = [])
  263. {
  264. $fields = array_diff($this->getTableFields(), $withoutFields);
  265. foreach ($fields as &$field) {
  266. $field = "$alias.$field";
  267. }
  268. return $fields;
  269. }
  270. /**
  271. * 多字段增减
  272. * @param array|int|bool $where
  273. * @param array $incData //自增字段
  274. * @param array $decData //自减字段
  275. * @param array $data //正常update字段
  276. * @return mixed
  277. */
  278. protected function setIncDec($where,array $incData,array $decData,array $data=[])
  279. {
  280. if (is_numeric($where)) {
  281. $where = [$this->getPk() => (int)$where];
  282. }
  283. $query = $this->where($where);
  284. foreach ($incData as $field=>$step){
  285. $query->inc($field, (float)$step);
  286. }
  287. foreach ($decData as $field=>$step){
  288. $query->dec($field, (float)$step);
  289. }
  290. return $query->update($data);
  291. }
  292. }