ModelTrait.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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|bool
  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. // var_dump(strpos($fieldOr[0], '.'));
  154. if (!empty($fieldOr) && is_array($fieldOr) && isset($fieldOr[0])) {
  155. if (($count = strpos($fieldOr[0], '.')) === false) {
  156. if (isset($where[$fieldOr[0]]) && $where[$fieldOr[0]] != '') {
  157. $model = $model->where(self::get_field($fieldOr), $like, "%" . $where[$fieldOr[0]] . "%");
  158. }
  159. } else {
  160. // var_dump(111);
  161. $item_l = substr($fieldOr[0], $count + 1);
  162. // var_dump($item_l);
  163. // var_dump($where[$item_l]);
  164. if (isset($where[$item_l]) && $where[$item_l] != '') {
  165. $model = $model->where(self::get_field($fieldOr), $like, "%" . $where[$item_l] . "%");
  166. }
  167. }
  168. }
  169. // var_dump($fieldOr);
  170. unset($count, $key, $item, $item_l);
  171. return $model;
  172. }
  173. /**
  174. * 字符串拼接
  175. * @param int|array $id
  176. * @param string $str
  177. * @return string
  178. */
  179. private static function get_field($id, $str = '|')
  180. {
  181. if (is_array($id)) {
  182. $sql = "";
  183. $i = 0;
  184. foreach ($id as $val) {
  185. $i++;
  186. if ($i < count($id)) {
  187. $sql .= $val . $str;
  188. } else {
  189. $sql .= $val;
  190. }
  191. }
  192. return $sql;
  193. } else {
  194. return $id;
  195. }
  196. }
  197. /**
  198. * 条件切割
  199. * @param string $order
  200. * @param string $file
  201. * @return string
  202. */
  203. public static function setOrder($order, $file = '-')
  204. {
  205. if (empty($order)) return '';
  206. return str_replace($file, ' ', $order);
  207. }
  208. /**
  209. * 获取时间段之间的model
  210. * @param int|string $time
  211. * @param string $ceil
  212. * @return array
  213. */
  214. public static function getModelTime($where, $model = null, $prefix = 'add_time', $data = 'data', $field = ' - ')
  215. {
  216. if ($model == null) $model = new self;
  217. if (!isset($where[$data])) return $model;
  218. switch ($where[$data]) {
  219. case 'today':
  220. case 'week':
  221. case 'month':
  222. case 'year':
  223. case 'yesterday':
  224. $model = $model->whereTime($prefix, $where[$data]);
  225. break;
  226. case 'quarter':
  227. list($startTime, $endTime) = self::getMonth();
  228. $model = $model->where($prefix, 'between', [strtotime($startTime), strtotime($endTime)]);
  229. // $model = $model->where($prefix, '<', strtotime($endTime));
  230. break;
  231. case 'lately7':
  232. $model = $model->where($prefix, 'between', [strtotime("-7 day"), time()]);
  233. break;
  234. case 'lately30':
  235. $model = $model->where($prefix, 'between', [strtotime("-30 day"), time()]);
  236. break;
  237. default:
  238. if (strstr($where[$data], $field) !== false) {
  239. list($startTime, $endTime) = explode($field, $where[$data]);
  240. $model = $model->where($prefix, 'between', [strtotime($startTime), bcadd(strtotime($endTime), 86400, 0)]);
  241. // $model = $model->where($prefix, '<',);
  242. }
  243. break;
  244. }
  245. return $model;
  246. }
  247. /**
  248. * 获取去除html去除空格去除软回车,软换行,转换过后的字符串
  249. * @param string $str
  250. * @return string
  251. */
  252. public static function HtmlToMbStr($str)
  253. {
  254. return trim(strip_tags(str_replace(["\n", "\t", "\r", " ", "&nbsp;"], '', htmlspecialchars_decode($str))));
  255. }
  256. /**
  257. * 截取中文指定字节
  258. * @param string $str
  259. * @param int $utf8len
  260. * @param string $chaet
  261. * @param string $file
  262. * @return string
  263. */
  264. public static function getSubstrUTf8($str, $utf8len = 100, $chaet = 'UTF-8', $file = '....')
  265. {
  266. if (mb_strlen($str, $chaet) > $utf8len) {
  267. $str = mb_substr($str, 0, $utf8len, $chaet) . $file;
  268. }
  269. return $str;
  270. }
  271. /**
  272. * 获取本季度 time
  273. * @param int|string $time
  274. * @param string $ceil
  275. * @return array
  276. */
  277. public static function getMonth($time = '', $ceil = 0)
  278. {
  279. if ($ceil != 0)
  280. $season = ceil(date('n') / 3) - $ceil;
  281. else
  282. $season = ceil(date('n') / 3);
  283. $firstday = date('Y-m-01', mktime(0, 0, 0, ($season - 1) * 3 + 1, 1, date('Y')));
  284. $lastday = date('Y-m-t', mktime(0, 0, 0, $season * 3, 1, date('Y')));
  285. return array($firstday, $lastday);
  286. }
  287. /**
  288. * 高精度 加法
  289. * @param int|string $uid id
  290. * @param string $decField 相加的字段
  291. * @param float|int $dec 加的值
  292. * @param string $keyField id的字段
  293. * @param int $acc 精度
  294. * @return bool
  295. */
  296. public static function bcInc($key, $incField, $inc, $keyField = null, $acc = 2)
  297. {
  298. if (!is_numeric($inc)) return false;
  299. $model = new self();
  300. if ($keyField === null) $keyField = $model->getPk();
  301. $result = self::where($keyField, $key)->find();
  302. if (!$result) return false;
  303. $new = bcadd($result[$incField], $inc, $acc);
  304. $result->$incField = $new;
  305. return false !== $result->save();
  306. // return false !== $model->where($keyField,$key)->update([$incField=>$new]);
  307. }
  308. /**
  309. * 高精度 减法
  310. * @param int|string $uid id
  311. * @param string $decField 相减的字段
  312. * @param float|int $dec 减的值
  313. * @param string $keyField id的字段
  314. * @param bool $minus 是否可以为负数
  315. * @param int $acc 精度
  316. * @return bool
  317. */
  318. public static function bcDec($key, $decField, $dec, $keyField = null, $minus = false, $acc = 2)
  319. {
  320. if (!is_numeric($dec)) return false;
  321. $model = new self();
  322. if ($keyField === null) $keyField = $model->getPk();
  323. $result = self::where($keyField, $key)->find();
  324. if (!$result) return false;
  325. if (!$minus && $result[$decField] < $dec) return false;
  326. $new = bcsub($result[$decField], $dec, $acc);
  327. $result->$decField = $new;
  328. return false !== $result->save();
  329. // return false !== $model->where($keyField,$key)->update([$decField=>$new]);
  330. }
  331. /**
  332. * @param null $model
  333. * @return Model
  334. */
  335. protected static function getSelfModel($model = null)
  336. {
  337. return $model == null ? (new self()) : $model;
  338. }
  339. }