BaseModel.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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|static|null|false
  48. */
  49. public static function get($data, $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)
  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()
  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 = [])
  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($alias = '', $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}."
  127. . (isset($item[2]) ? $item[2] : $item[1]));
  128. endforeach; endif;
  129. return $query;
  130. }
  131. /**
  132. * 更新数据
  133. * 重写\think\Model::update方法, 目的可以返回更新的状态bool
  134. * @access public
  135. * @param array $data 数据数组
  136. * @param array $where 更新条件
  137. * @param array $allowField 允许字段
  138. * @return bool
  139. */
  140. public static function updateBase(array $data, array $where = [], array $allowField = []): bool
  141. {
  142. $model = new static;
  143. if (!empty($allowField)) {
  144. $model->allowField($allowField);
  145. }
  146. if (!empty($where)) {
  147. $model->setUpdateWhere($where);
  148. }
  149. return $model->exists(true)->save($data);
  150. }
  151. /**
  152. * 批量更新数据(支持带where条件)
  153. * @param iterable $dataSet [0 => ['data'=>[], 'where'=>[]]]
  154. * @return array|false
  155. */
  156. public function updateAll(iterable $dataSet)
  157. {
  158. if (empty($dataSet)) {
  159. return false;
  160. }
  161. return $this->transaction(function () use ($dataSet) {
  162. $result = [];
  163. foreach ($dataSet as $key => $item) {
  164. $result[$key] = self::updateBase($item['data'], $item['where']);
  165. }
  166. return $result;
  167. });
  168. }
  169. /**
  170. * 批量新增数据
  171. * @param iterable $dataSet [0 => ['id'=>10001, 'name'=>'wang']]
  172. * @return array|false
  173. */
  174. public function addAll(iterable $dataSet)
  175. {
  176. if (empty($dataSet)) {
  177. return false;
  178. }
  179. return $this->transaction(function () use ($dataSet) {
  180. $result = [];
  181. foreach ($dataSet as $key => $item) {
  182. $result[$key] = self::create($item, $this->field);
  183. }
  184. return $result;
  185. });
  186. }
  187. /**
  188. * 删除记录
  189. * @param array $where
  190. * 方式1: ['goods_id' => $goodsId]
  191. * 方式2: [
  192. * ['store_user_id', '=', $storeUserId],
  193. * ['role_id', 'in', $deleteRoleIds]
  194. * ]
  195. * @return int
  196. */
  197. public static function deleteAll(array $where)
  198. {
  199. return (new static)->where($where)->delete();
  200. }
  201. /**
  202. * 返回错误信息
  203. * @return string
  204. */
  205. public function getError()
  206. {
  207. return empty($this->error) ? false : $this->error;
  208. }
  209. /**
  210. * 字段值增长
  211. * @param array|int|bool $where
  212. * @param string $field
  213. * @param float $step
  214. * @return mixed
  215. */
  216. protected function setInc($where, string $field, float $step = 1)
  217. {
  218. if (is_numeric($where)) {
  219. $where = [$this->getPk() => (int)$where];
  220. }
  221. return $this->where($where)->inc($field, $step)->update();
  222. }
  223. /**
  224. * 字段值消减
  225. * @param array|int|bool $where
  226. * @param string $field
  227. * @param float $step
  228. * @return mixed
  229. */
  230. protected function setDec($where, string $field, float $step = 1)
  231. {
  232. return $this->where($where)->dec($field, $step)->update();
  233. }
  234. /**
  235. * 实例化新查询对象
  236. * @return \think\db\BaseQuery
  237. */
  238. protected function getNewQuery()
  239. {
  240. return $this->db();
  241. }
  242. /**
  243. * 新增hidden属性
  244. * @param array $hidden
  245. * @return $this
  246. */
  247. protected function addHidden(array $hidden)
  248. {
  249. $this->hidden = array_merge($this->hidden, $hidden);
  250. return $this;
  251. }
  252. /**
  253. * 生成字段列表(字段加上$alias别名)
  254. * @param string $alias 别名
  255. * @param array $withoutFields 排除的字段
  256. * @return array
  257. */
  258. protected function getAliasFields(string $alias, $withoutFields = [])
  259. {
  260. $fields = array_diff($this->getTableFields(), $withoutFields);
  261. foreach ($fields as &$field) {
  262. $field = "$alias.$field";
  263. }
  264. return $fields;
  265. }
  266. }