ModelTrait.php 11 KB

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