User.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.thinkphp.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: thinkphp <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\common\model;
  13. use cores\BaseModel;
  14. use think\model\Collection;
  15. use think\model\relation\HasOne;
  16. use think\model\relation\HasMany;
  17. use think\model\relation\BelongsTo;
  18. use app\common\model\user\PointsLog as PointsLogModel;
  19. use think\Paginator;
  20. /**
  21. * 用户模型类
  22. * Class User
  23. * @package app\common\model
  24. */
  25. class User extends BaseModel
  26. {
  27. // 定义表名
  28. protected $name = 'user';
  29. // 定义主键
  30. protected $pk = 'user_id';
  31. // 性别
  32. private $gender = [0 => '未知', 1 => '男', 2 => '女'];
  33. /**
  34. * 获取列表
  35. * @param array $param 查询条件
  36. * @param int $listRows 分页数量
  37. * @return mixed
  38. * @throws \think\db\exception\DbException
  39. */
  40. public function getList(array $param = [], int $listRows = 15)
  41. {
  42. // 筛选条件
  43. $query = $this->getQueryFilter($param);
  44. // 排序条件
  45. $sort = $this->setQuerySort($param);
  46. // 执行查询
  47. $userId = isset($param['user_id'])? intval($param['user_id']) : 0;
  48. $lockedUids = $userId? UserInfo::getLockedIds($userId) : [];
  49. $list = $query->alias($this->name)
  50. ->leftJoin('user_info ui','ui.user_id='.$this->name.'.user_id')
  51. ->leftJoin('school_speciality sp','sp.speciality_id=ui.speciality')
  52. ->leftJoin('source_shools s','s.source_shools_id=ui.school_id')
  53. ->field($this->name.'.*,ui.admission_year,ui.position,s.region_id,s.source_shools_name as school_name,sp.speciality_name');
  54. if($lockedUids){
  55. $list = $list->orderRaw("field(".$this->name.".user_id,".implode(',', $lockedUids).")");
  56. }
  57. $list = $list->order($sort)
  58. ->paginate($listRows);
  59. // 整理列表数据并返回
  60. return $list;
  61. }
  62. /**
  63. * 获取默认解锁用户列表
  64. * @param array $param 查询条件
  65. * @return mixed
  66. * @throws \think\db\exception\DbException
  67. */
  68. public function getLockedList(array $param = [])
  69. {
  70. // 筛选条件
  71. $query = $this->getNewQuery();
  72. // 执行查询
  73. $userId = isset($param['user_id'])? intval($param['user_id']) : 0;
  74. $lockedUids = $userId? UserInfo::getLockedIds($userId) : [];
  75. $list = $query->alias($this->name)
  76. ->where([$this->name.'.is_delete'=>0,$this->name.'.status'=>1])
  77. ->where(function($query) use ($lockedUids){
  78. if($lockedUids){
  79. $query->where($this->name.'.user_id', $lockedUids);
  80. }
  81. })
  82. ->leftJoin('user_info ui','ui.user_id='.$this->name.'.user_id')
  83. ->leftJoin('school_speciality sp','sp.speciality_id=ui.speciality')
  84. ->leftJoin('source_shools s','s.source_shools_id=ui.school_id')
  85. ->field($this->name.'.*,ui.admission_year,ui.position,s.region_id,s.source_shools_name as school_name,sp.speciality_name')
  86. ->order($this->name.'.user_id desc')
  87. ->select();
  88. // 整理列表数据并返回
  89. return $list;
  90. }
  91. /**
  92. * 设置商品展示的数据
  93. * @param Collection|Paginator $list 商品列表
  94. * @param callable|null $callback 回调函数
  95. * @return mixed
  96. */
  97. protected function setListData($list, callable $callback = null)
  98. {
  99. if ($list->isEmpty()) return $list;
  100. // 遍历商品列表整理数据
  101. foreach ($list as &$item) {
  102. $data = $this->setData($item, $callback);
  103. }
  104. return $list;
  105. }
  106. /**
  107. * 整理数据
  108. * @param Collection|static $info
  109. * @param callable|null $callback
  110. * @return mixed
  111. */
  112. protected function setData($info, callable $callback = null)
  113. {
  114. // 回调函数
  115. is_callable($callback) && call_user_func($callback, $info);
  116. return $info->hidden(array_merge($this->hidden, ['albums']));
  117. }
  118. /**
  119. * 检索查询条件
  120. * @param array $params
  121. * @return \think\db\BaseQuery
  122. */
  123. private function getQueryFilter(array $params)
  124. {
  125. $filter = [];
  126. // 实例化新查询对象
  127. $query = $this->getNewQuery();
  128. // 区
  129. !empty($params['region_id']) && $filter[] = ['s.region_id', '=', "{$params['region_id']}"];
  130. // 市
  131. !empty($params['city_id']) && $filter[] = ['s.city_id', '=', "{$params['city_id']}"];
  132. // 省
  133. !empty($params['province_id']) && $filter[] = ['s.province_id', '=', "{$params['province_id']}"];
  134. // 用户状态
  135. !empty($params['status']) && $filter[] = [$this->name.'.status', '=', "{$params['status']}"];
  136. // 审核状态
  137. !empty($params['ui.status']) && $filter[] = ['ui.status', '=', "{$params['ui.status']}"];
  138. // 生源学校
  139. !empty($params['school_id']) && $filter[] = ['ui.school_id', '=', "{$params['school_id']}"];
  140. // 用户类型
  141. !empty($params['user_type']) && $filter[] = [$this->name.'.user_type', '=', "{$params['user_type']}"];
  142. // 实例化新查询对象
  143. return $query->where($filter)->where(function($query) use ($params){
  144. // 关键词
  145. if(!empty($params['keyword'])){
  146. $query->where('s.source_shools_name','like', "%{$params['keyword']}%")
  147. ->whereOr('sp.speciality_name','like',"%{$params['keyword']}%");
  148. }
  149. // 学长学姐筛选
  150. $admissionYear = isset($params['admission_year'])? intval($params['admission_year']) : -1;
  151. if($admissionYear>0){
  152. $query->where('ui.admission_year','<', $admissionYear)->where('ui.admission_year','>', 0);
  153. }else if(isset($params['admission_year'])){
  154. $query->where('ui.admission_year','>', 0);
  155. }
  156. });
  157. }
  158. /**
  159. * 检索排序条件
  160. * @param array $param
  161. * @return array|string[]
  162. */
  163. private function setQuerySort(array $param = [])
  164. {
  165. $params = $this->setQueryDefaultValue($param, [
  166. 'sortType' => 'all', // 排序类型
  167. $this->name.'.create_time' => false, // 热门排序 (true高到低 false低到高)
  168. ]);
  169. // 排序规则
  170. $sort = [];
  171. if ($params['sortType'] === 'all') {
  172. $sort = [$this->name.'.create_time' => 'desc'];
  173. } elseif ($params['sortType'] === 'view') {
  174. $sort = [$this->name.'.id' => 'desc'];
  175. }
  176. return array_merge($sort, [$this->getPk() => 'desc']);
  177. }
  178. /**
  179. * 关联用户头像表
  180. * @return HasOne
  181. */
  182. public function avatar(): HasOne
  183. {
  184. return $this->hasOne('UploadFile', 'file_id', 'avatar_id')
  185. ->bind(['avatar_url' => 'preview_url']);
  186. }
  187. /**
  188. * 用户资料表
  189. * @return HasOne
  190. */
  191. public function info(): HasOne
  192. {
  193. return $this->hasOne("UserInfo", 'user_id', 'user_id')
  194. ->field('user_id,school_id,agent_id,position,speciality,qq,parent_name,admission_year,status');
  195. }
  196. /**
  197. * 关联会员等级表
  198. * @return BelongsTo
  199. */
  200. public function grade(): BelongsTo
  201. {
  202. $module = self::getCalledModule();
  203. return $this->belongsTo("app\\{$module}\\model\\user\\Grade", 'grade_id');
  204. }
  205. /**
  206. * 关联收货地址表
  207. * @return HasMany
  208. */
  209. public function address(): HasMany
  210. {
  211. return $this->hasMany('UserAddress');
  212. }
  213. /**
  214. * 关联收货地址表 (默认地址)
  215. * @return BelongsTo
  216. */
  217. public function addressDefault(): BelongsTo
  218. {
  219. return $this->belongsTo('UserAddress', 'address_id');
  220. }
  221. /**
  222. * 获取器:显示性别
  223. * @param $value
  224. * @return string
  225. */
  226. public function getGenderAttr($value): string
  227. {
  228. return $this->gender[$value];
  229. }
  230. /**
  231. * 获取用户信息
  232. * @param $where
  233. * @param array $with
  234. * @return static|array|false|null
  235. */
  236. public static function detail($where, array $with = [])
  237. {
  238. $filter = ['is_delete' => 0];
  239. if (is_array($where)) {
  240. $filter = array_merge($filter, $where);
  241. } else {
  242. $filter['user_id'] = (int)$where;
  243. }
  244. return static::get($filter, $with);
  245. }
  246. /**
  247. * 获取用户信息
  248. * @param $where
  249. * @param array $with
  250. * @return static|array|false|null
  251. */
  252. public static function cacheDetail($where, array $with = [])
  253. {
  254. $cacheKey = "caches:users:detail:".(!is_array($where)? $where.'_' : md5(json_encode($where)));
  255. $data = \think\facade\Cache::get($cacheKey);
  256. if($data){
  257. return $data;
  258. }
  259. $filter = ['is_delete' => 0];
  260. if (is_array($where)) {
  261. $filter = array_merge($filter, $where);
  262. } else {
  263. $filter['user_id'] = (int)$where;
  264. }
  265. $info = static::get($filter, $with);
  266. if($info){
  267. $info['avatar'] = isset($info['avatar'])? $info['avatar'] : [];
  268. $info['info'] = isset($info['info'])? $info['info'] : [];
  269. $info['info'] = isset($info['info'])? $info['info'] : [];
  270. \think\facade\Cache::set($cacheKey, $info, rand(5, 10));
  271. }
  272. return $info;
  273. }
  274. /**
  275. * 累积用户的实际消费金额
  276. * @param int $userId
  277. * @param float $expendMoney
  278. * @return mixed
  279. */
  280. public static function setIncUserExpend(int $userId, float $expendMoney)
  281. {
  282. return (new static)->setInc($userId, 'expend_money', $expendMoney);
  283. }
  284. /**
  285. * 累积用户可用余额
  286. * @param int $userId
  287. * @param float $money
  288. * @return mixed
  289. */
  290. public static function setIncBalance(int $userId, float $money)
  291. {
  292. return (new static)->setInc($userId, 'balance', $money);
  293. }
  294. /**
  295. * 消减用户可用余额
  296. * @param int $userId
  297. * @param float $money
  298. * @return mixed
  299. */
  300. public static function setDecBalance(int $userId, float $money)
  301. {
  302. return (new static)->setDec([['user_id', '=', $userId]], 'balance', $money);
  303. }
  304. /**
  305. * 指定会员等级下是否存在用户
  306. * @param int $gradeId
  307. * @return bool
  308. */
  309. public static function checkExistByGradeId(int $gradeId): bool
  310. {
  311. $model = new static;
  312. return (bool)$model->where('grade_id', '=', (int)$gradeId)
  313. ->where('is_delete', '=', 0)
  314. ->value($model->getPk());
  315. }
  316. /**
  317. * 指定的手机号是否已存在
  318. * @param string $mobile
  319. * @return bool
  320. */
  321. public static function checkExistByMobile(string $mobile): bool
  322. {
  323. $model = new static;
  324. return (bool)$model->where('mobile', '=', $mobile)
  325. ->where('is_delete', '=', 0)
  326. ->value($model->getPk());
  327. }
  328. /**
  329. * 累积用户总消费金额
  330. * @param int $userId
  331. * @param float $money
  332. * @return mixed
  333. */
  334. public static function setIncPayMoney(int $userId, float $money)
  335. {
  336. return (new static)->setInc($userId, 'pay_money', $money);
  337. }
  338. /**
  339. * 累积用户实际消费的金额 (批量)
  340. * @param array $data
  341. * @return bool
  342. */
  343. public function onBatchIncExpendMoney(array $data): bool
  344. {
  345. foreach ($data as $userId => $expendMoney) {
  346. static::setIncUserExpend($userId, (float)$expendMoney);
  347. }
  348. return true;
  349. }
  350. /**
  351. * 累积用户的可用积分数量 (批量)
  352. * @param array $data
  353. * @return bool
  354. */
  355. public function onBatchIncPoints(array $data): bool
  356. {
  357. foreach ($data as $userId => $value) {
  358. $this->setInc($userId, 'points', $value);
  359. }
  360. return true;
  361. }
  362. /**
  363. * 累积用户的可用积分
  364. * @param int $userId 用户ID
  365. * @param int $points 累计的积分
  366. * @param string $describe
  367. * @return mixed
  368. */
  369. public static function setIncPoints(int $userId, int $points, string $describe)
  370. {
  371. // 新增积分变动明细
  372. PointsLogModel::add([
  373. 'user_id' => $userId,
  374. 'value' => $points,
  375. 'describe' => $describe,
  376. ]);
  377. // 更新用户可用积分
  378. return (new static)->setInc($userId, 'points', $points);
  379. }
  380. }