ModelTrait.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. <?php
  2. namespace crmeb\traits;
  3. use think\db\Query;
  4. use think\Model;
  5. trait ModelTrait
  6. {
  7. public static function get($where)
  8. {
  9. if (!is_array($where)) {
  10. return self::find($where);
  11. } else {
  12. return self::where($where)->find();
  13. }
  14. }
  15. public static function all($function)
  16. {
  17. $query = self::newQuery();
  18. $function($query);
  19. return $query->select();
  20. }
  21. /**
  22. * 添加多条数据
  23. * @param $group
  24. * @param bool $replace
  25. * @return mixed
  26. */
  27. public static function setAll($group, $replace = false)
  28. {
  29. return self::insertAll($group, $replace);
  30. }
  31. /**
  32. * 修改一条数据
  33. * @param $data
  34. * @param $id
  35. * @param $field
  36. * @return bool $type 返回成功失败
  37. */
  38. public static function edit($data, $id, $field = null)
  39. {
  40. $model = new self;
  41. if (!$field) $field = $model->getPk();
  42. // return false !== $model->update($data,[$field=>$id]);
  43. // return 0 < $model->update($data,[$field=>$id])->result;
  44. $res = $model->update($data, [$field => $id]);
  45. if (isset($res->result))
  46. return 0 < $res->result;
  47. else if (isset($res['data']['result']))
  48. return 0 < $res['data']['result'];
  49. else
  50. return false !== $res;
  51. }
  52. /**
  53. * 查询一条数据是否存在
  54. * @param $map
  55. * @param string $field
  56. * @return bool 是否存在
  57. */
  58. public static function be($map, $field = '')
  59. {
  60. $model = (new self);
  61. if (!is_array($map) && empty($field)) $field = $model->getPk();
  62. $map = !is_array($map) ? [$field => $map] : $map;
  63. return 0 < $model->where($map)->count();
  64. }
  65. /**
  66. * 删除一条数据
  67. * @param $id
  68. * @return bool $type 返回成功失败
  69. */
  70. public static function del($id)
  71. {
  72. return false !== self::destroy($id);
  73. }
  74. /**
  75. * 分页
  76. * @param null $model 模型
  77. * @param null $eachFn 处理结果函数
  78. * @param array $params 分页参数
  79. * @param int $limit 分页数
  80. * @return object
  81. */
  82. public static function page($model = null, $eachFn = null, $params = [], $limit = 20)
  83. {
  84. if (is_numeric($eachFn) && is_numeric($model)) {
  85. return parent::page($model, $eachFn);
  86. }
  87. if (is_numeric($eachFn)) {
  88. $limit = $eachFn;
  89. $eachFn = null;
  90. } else if (is_array($eachFn)) {
  91. $params = $eachFn;
  92. $eachFn = null;
  93. }
  94. if (is_callable($model)) {
  95. $eachFn = $model;
  96. $model = null;
  97. } elseif (is_numeric($model)) {
  98. $limit = $model;
  99. $model = null;
  100. } elseif (is_array($model)) {
  101. $params = $model;
  102. $model = null;
  103. }
  104. if (is_numeric($params)) {
  105. $limit = $params;
  106. $params = [];
  107. }
  108. $listRows = [
  109. 'list_rows' => $limit,
  110. 'query' => $params
  111. ];
  112. $paginate = $model === null ? self::paginate($listRows, false) : $model->paginate($listRows, false);
  113. $list = is_callable($eachFn) ? $paginate->each($eachFn) : $paginate;
  114. $page = $list->render();
  115. $total = $list->total();
  116. return compact('list', 'page', 'total');
  117. }
  118. /**
  119. * 获取分页 生成where 条件和 whereOr 支持多表查询生成条件
  120. * @param object $model 模型对象
  121. * @param array $where 需要检索的数组
  122. * @param array $field where字段名
  123. * @param array $fieldOr whereOr字段名
  124. * @param array $fun 闭包函数
  125. * @param string $like 模糊查找 关键字
  126. * @return array
  127. */
  128. public static function setWherePage($model = null, $where = [], $field = [], $fieldOr = [], $fun = null, $like = 'LIKE')
  129. {
  130. if (!is_array($where) || !is_array($field)) return false;
  131. if ($model === null) $model = new self();
  132. //处理等于行查询
  133. foreach ($field as $key => $item) {
  134. if (($count = strpos($item, '.')) === false) {
  135. if (isset($where[$item]) && $where[$item] != '') {
  136. $model = $model->where($item, $where[$item]);
  137. }
  138. } else {
  139. $item_l = substr($item, $count + 1);
  140. if (isset($where[$item_l]) && $where[$item_l] != '') {
  141. $model = $model->where($item, $where[$item_l]);
  142. }
  143. }
  144. }
  145. //回收变量
  146. unset($count, $key, $item, $item_l);
  147. //处理模糊查询
  148. if (!empty($fieldOr) && is_array($fieldOr) && isset($fieldOr[0])) {
  149. if (($count = strpos($fieldOr[0], '.')) === false) {
  150. if (isset($where[$fieldOr[0]]) && $where[$fieldOr[0]] != '') {
  151. $model = $model->where(self::get_field($fieldOr), $like, "%" . $where[$fieldOr[0]] . "%");
  152. }
  153. } else {
  154. $item_l = substr($fieldOr[0], $count + 1);
  155. if (isset($where[$item_l]) && $where[$item_l] != '') {
  156. $model = $model->where(self::get_field($fieldOr), $like, "%" . $where[$item_l] . "%");
  157. }
  158. }
  159. }
  160. unset($count, $key, $item, $item_l);
  161. return $model;
  162. }
  163. /**
  164. * 字符串拼接
  165. * @param int|array $id
  166. * @param string $str
  167. * @return string
  168. */
  169. private static function get_field($id, $str = '|')
  170. {
  171. if (is_array($id)) {
  172. $sql = "";
  173. $i = 0;
  174. foreach ($id as $val) {
  175. $i++;
  176. if ($i < count($id)) {
  177. $sql .= $val . $str;
  178. } else {
  179. $sql .= $val;
  180. }
  181. }
  182. return $sql;
  183. } else {
  184. return $id;
  185. }
  186. }
  187. /**
  188. * 条件切割
  189. * @param string $order
  190. * @param string $file
  191. * @return string
  192. */
  193. public static function setOrder($order, $file = '-')
  194. {
  195. if (empty($order)) return '';
  196. return str_replace($file, ' ', $order);
  197. }
  198. /**
  199. * 获取时间段之间的model
  200. * @param int|string $time
  201. * @param string $ceil
  202. * @return object
  203. */
  204. public static function getModelTime($where, $model = null, $prefix = 'add_time', $data = 'data', $field = ' - ')
  205. {
  206. if ($model == null) $model = new self;
  207. if (!isset($where[$data])) return $model;
  208. switch ($where[$data]) {
  209. case 'today':
  210. case 'week':
  211. case 'month':
  212. case 'year':
  213. case 'yesterday':
  214. $model = $model->whereTime($prefix, $where[$data]);
  215. break;
  216. case 'quarter':
  217. list($startTime, $endTime) = self::getMonth();
  218. $model = $model->where($prefix, '>', strtotime($startTime));
  219. $model = $model->where($prefix, '<', strtotime($endTime));
  220. break;
  221. case 'lately7':
  222. $model = $model->where($prefix, 'between', [strtotime("-7 day"), time()]);
  223. break;
  224. case 'lately30':
  225. $model = $model->where($prefix, 'between', [strtotime("-30 day"), time()]);
  226. break;
  227. default:
  228. if (strstr($where[$data], $field) !== false) {
  229. list($startTime, $endTime) = explode($field, $where[$data]);
  230. $model = $model->where($prefix, '>', strtotime($startTime));
  231. $model = $model->where($prefix, '<', bcadd(strtotime($endTime), 86400, 0));
  232. }
  233. break;
  234. }
  235. return $model;
  236. }
  237. /**
  238. * 获取去除html去除空格去除软回车,软换行,转换过后的字符串
  239. * @param string $str
  240. * @return string
  241. */
  242. public static function HtmlToMbStr($str)
  243. {
  244. return trim(strip_tags(str_replace(["\n", "\t", "\r", " ", "&nbsp;"], '', htmlspecialchars_decode($str))));
  245. }
  246. /**
  247. * 截取中文指定字节
  248. * @param string $str
  249. * @param int $utf8len
  250. * @param string $chaet
  251. * @param string $file
  252. * @return string
  253. */
  254. public static function getSubstrUTf8($str, $utf8len = 100, $chaet = 'UTF-8', $file = '....')
  255. {
  256. if (mb_strlen($str, $chaet) > $utf8len) {
  257. $str = mb_substr($str, 0, $utf8len, $chaet) . $file;
  258. }
  259. return $str;
  260. }
  261. /**
  262. * 获取本季度 time
  263. * @param int|string $time
  264. * @param string $ceil
  265. * @return array
  266. */
  267. public static function getMonth($time = '', $ceil = 0)
  268. {
  269. if ($ceil != 0)
  270. $season = ceil(date('n') / 3) - $ceil;
  271. else
  272. $season = ceil(date('n') / 3);
  273. $firstday = date('Y-m-01', mktime(0, 0, 0, ($season - 1) * 3 + 1, 1, date('Y')));
  274. $lastday = date('Y-m-t', mktime(0, 0, 0, $season * 3, 1, date('Y')));
  275. return array($firstday, $lastday);
  276. }
  277. /**
  278. * 高精度 加法
  279. * @param int|string $uid id
  280. * @param string $decField 相加的字段
  281. * @param float|int $dec 加的值
  282. * @param string $keyField id的字段
  283. * @param int $acc 精度
  284. * @return bool
  285. */
  286. public static function bcInc($key, $incField, $inc, $keyField = null, $acc = 2)
  287. {
  288. if (!is_numeric($inc)) return false;
  289. $model = new self();
  290. if ($keyField === null) $keyField = $model->getPk();
  291. $result = self::where($keyField, $key)->find();
  292. if (!$result) return false;
  293. $new = bcadd($result[$incField], $inc, $acc);
  294. $result->$incField = $new;
  295. return false !== $result->save();
  296. // return false !== $model->where($keyField,$key)->update([$incField=>$new]);
  297. }
  298. /**
  299. * 高精度 减法
  300. * @param int|string $uid id
  301. * @param string $decField 相减的字段
  302. * @param float|int $dec 减的值
  303. * @param string $keyField id的字段
  304. * @param bool $minus 是否可以为负数
  305. * @param int $acc 精度
  306. * @return bool
  307. */
  308. public static function bcDec($key, $decField, $dec, $keyField = null, $minus = false, $acc = 2)
  309. {
  310. if (!is_numeric($dec)) return false;
  311. $model = new self();
  312. if ($keyField === null) $keyField = $model->getPk();
  313. $result = self::where($keyField, $key)->find();
  314. if (!$result) return false;
  315. if (!$minus && $result[$decField] < $dec) return false;
  316. $new = bcsub($result[$decField], $dec, $acc);
  317. $result->$decField = $new;
  318. return false !== $result->save();
  319. // return false !== $model->where($keyField,$key)->update([$decField=>$new]);
  320. }
  321. /**
  322. * @param null $model
  323. * @return Model
  324. */
  325. protected static function getSelfModel($model = null)
  326. {
  327. return $model == null ? (new self()) : $model;
  328. }
  329. }