ModelTrait.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. public static function getModelTime1($where, $model = null, $prefix = 'add_time', $data = 'data', $field = ' - ')
  243. {
  244. if ($model == null) $model = new self;
  245. if (!isset($where[$data])) return $model;
  246. switch ($where[$data]) {
  247. case 'today':
  248. case 'week':
  249. case 'month':
  250. case 'year':
  251. case 'yesterday':
  252. $model = $model->whereTime($prefix, $where[$data]);
  253. break;
  254. case 'quarter':
  255. list($startTime, $endTime) = self::getMonth();
  256. $model = $model->where($prefix, '>', strtotime($startTime));
  257. $model = $model->where($prefix, '<', strtotime($endTime));
  258. break;
  259. case 'lately7':
  260. $model = $model->where($prefix, 'between', [strtotime("-7 day"), time()]);
  261. break;
  262. case 'lately30':
  263. $model = $model->where($prefix, 'between', [strtotime("-30 day"), time()]);
  264. break;
  265. default:
  266. if (strstr($where[$data], $field) !== false) {
  267. list($startTime, $endTime) = explode($field, $where[$data]);
  268. $model = $model->where($prefix, '>', $startTime);
  269. $model = $model->where($prefix, '<', date("Y-m-d H:i:s",bcadd(strtotime($endTime), 86400, 0)));
  270. }
  271. break;
  272. }
  273. return $model;
  274. }
  275. /**
  276. * 获取去除html去除空格去除软回车,软换行,转换过后的字符串
  277. * @param string $str
  278. * @return string
  279. */
  280. public static function HtmlToMbStr($str)
  281. {
  282. return trim(strip_tags(str_replace(["\n", "\t", "\r", " ", "&nbsp;"], '', htmlspecialchars_decode($str))));
  283. }
  284. /**
  285. * 截取中文指定字节
  286. * @param string $str
  287. * @param int $utf8len
  288. * @param string $chaet
  289. * @param string $file
  290. * @return string
  291. */
  292. public static function getSubstrUTf8($str, $utf8len = 100, $chaet = 'UTF-8', $file = '....')
  293. {
  294. if (mb_strlen($str, $chaet) > $utf8len) {
  295. $str = mb_substr($str, 0, $utf8len, $chaet) . $file;
  296. }
  297. return $str;
  298. }
  299. /**
  300. * 获取本季度 time
  301. * @param int|string $time
  302. * @param string $ceil
  303. * @return array
  304. */
  305. public static function getMonth($time = '', $ceil = 0)
  306. {
  307. if ($ceil != 0)
  308. $season = ceil(date('n') / 3) - $ceil;
  309. else
  310. $season = ceil(date('n') / 3);
  311. $firstday = date('Y-m-01', mktime(0, 0, 0, ($season - 1) * 3 + 1, 1, date('Y')));
  312. $lastday = date('Y-m-t', mktime(0, 0, 0, $season * 3, 1, date('Y')));
  313. return array($firstday, $lastday);
  314. }
  315. /**
  316. * 高精度 加法
  317. * @param int|string $uid id
  318. * @param string $decField 相加的字段
  319. * @param float|int $dec 加的值
  320. * @param string $keyField id的字段
  321. * @param int $acc 精度
  322. * @return bool
  323. */
  324. public static function bcInc($key, $incField, $inc, $keyField = null, $acc = 2)
  325. {
  326. if (!is_numeric($inc)) return false;
  327. $model = new self();
  328. if ($keyField === null) $keyField = $model->getPk();
  329. $result = self::where($keyField, $key)->find();
  330. if (!$result) return false;
  331. $new = bcadd($result[$incField], $inc, $acc);
  332. $result->$incField = $new;
  333. return false !== $result->save();
  334. // return false !== $model->where($keyField,$key)->update([$incField=>$new]);
  335. }
  336. /**
  337. * 高精度 减法
  338. * @param int|string $uid id
  339. * @param string $decField 相减的字段
  340. * @param float|int $dec 减的值
  341. * @param string $keyField id的字段
  342. * @param bool $minus 是否可以为负数
  343. * @param int $acc 精度
  344. * @return bool
  345. */
  346. public static function bcDec($key, $decField, $dec, $keyField = null, $minus = false, $acc = 2)
  347. {
  348. if (!is_numeric($dec)) return false;
  349. $model = new self();
  350. if ($keyField === null) $keyField = $model->getPk();
  351. $result = self::where($keyField, $key)->find();
  352. if (!$result) return false;
  353. if (!$minus && $result[$decField] < $dec) return false;
  354. $new = bcsub($result[$decField], $dec, $acc);
  355. $result->$decField = $new;
  356. return false !== $result->save();
  357. // return false !== $model->where($keyField,$key)->update([$decField=>$new]);
  358. }
  359. /**
  360. * @param null $model
  361. * @return Model
  362. */
  363. protected static function getSelfModel($model = null)
  364. {
  365. return $model == null ? (new self()) : $model;
  366. }
  367. }