ModelTrait.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2017/11/11
  6. */
  7. namespace traits;
  8. use think\db\Query;
  9. use think\Model;
  10. trait ModelTrait
  11. {
  12. /**
  13. * 添加一条数据
  14. * @param $data
  15. * @return object $model 数据对象
  16. */
  17. public static function set($data)
  18. {
  19. return self::create($data);
  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 array
  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. $paginate = $model === null ? self::paginate($limit,false,['query'=>$params]) : $model->paginate($limit,false,['query'=>$params]);
  109. $list = is_callable($eachFn) ? $paginate->each($eachFn) : $paginate;
  110. $page = $list->render();
  111. $total = $list->total();
  112. return compact('list','page','total');
  113. }
  114. /**
  115. * 获取分页 生成where 条件和 whereOr 支持多表查询生成条件
  116. * @param object $model 模型对象
  117. * @param array $where 需要检索的数组
  118. * @param array $field where字段名
  119. * @param array $fieldOr whereOr字段名
  120. * @param array $fun 闭包函数
  121. * @param string $like 模糊查找 关键字
  122. * @return array
  123. */
  124. public static function setWherePage($model=null,$where=[],$field=[],$fieldOr=[],$fun=null,$like='LIKE'){
  125. if(!is_array($where) || !is_array($field)) return false;
  126. if($model===null) $model=new self();
  127. //处理等于行查询
  128. foreach ($field as $key=>$item){
  129. if(($count=strpos($item,'.'))===false){
  130. if(isset($where[$item]) && $where[$item]!='') {
  131. $model=$model->where($item,$where[$item]);
  132. }
  133. }else{
  134. $item_l=substr($item,$count+1);
  135. if(isset($where[$item_l]) && $where[$item_l]!=''){
  136. $model=$model->where($item,$where[$item_l]);
  137. }
  138. }
  139. }
  140. //回收变量
  141. unset($count,$key,$item,$item_l);
  142. //处理模糊查询
  143. if(!empty($fieldOr) && is_array($fieldOr) && isset($fieldOr[0])){
  144. if(($count=strpos($fieldOr[0],'.'))===false){
  145. if(isset($where[$fieldOr[0]]) && $where[$fieldOr[0]]!='') {
  146. $model=$model->where(self::get_field($fieldOr),$like,"%".$where[$fieldOr[0]]."%");
  147. }
  148. }else{
  149. $item_l = substr($fieldOr[0],$count+1);
  150. if(isset($where[$item_l]) && $where[$item_l]!='') {
  151. $model=$model->where(self::get_field($fieldOr),$like,"%".$where[$item_l]."%");
  152. }
  153. }
  154. }
  155. unset($count,$key,$item,$item_l);
  156. return $model;
  157. }
  158. /**
  159. * 字符串拼接
  160. * @param int|array $id
  161. * @param string $str
  162. * @return string
  163. */
  164. private static function get_field($id,$str='|'){
  165. if(is_array($id)){
  166. $sql="";
  167. $i=0;
  168. foreach($id as $val){
  169. $i++;
  170. if($i<count($id)){
  171. $sql.=$val.$str;
  172. }else{
  173. $sql.=$val;
  174. }
  175. }
  176. return $sql;
  177. }else{
  178. return $id;
  179. }
  180. }
  181. /**
  182. * 条件切割
  183. * @param string $order
  184. * @param string $file
  185. * @return string
  186. */
  187. public static function setOrder($order,$file='-'){
  188. if(empty($order)) return '';
  189. return str_replace($file,' ',$order);
  190. }
  191. /**
  192. * 获取时间段之间的model
  193. * @param int|string $time
  194. * @param string $ceil
  195. * @return array
  196. */
  197. public static function getModelTime($where,$model=null,$prefix='add_time',$data='data',$field=' - '){
  198. if ($model === null) $model = new self;
  199. if(!isset($where[$data])) return $model;
  200. switch ($where[$data]){
  201. case 'today':case 'week':case 'month':case 'year':case 'yesterday':
  202. $model=$model->whereTime($prefix,$where[$data]);
  203. break;
  204. case 'quarter':
  205. list($startTime,$endTime)=self::getMonth();
  206. $model = $model->where($prefix, '>', strtotime($startTime));
  207. $model = $model->where($prefix, '<', strtotime($endTime));
  208. break;
  209. case 'lately7':
  210. $model = $model->where($prefix,'between',[strtotime("-7 day"),time()]);
  211. break;
  212. case 'lately30':
  213. $model = $model->where($prefix,'between',[strtotime("-30 day"),time()]);
  214. break;
  215. default:
  216. if(strstr($where[$data],$field)!==false){
  217. list($startTime, $endTime) = explode($field, $where[$data]);
  218. $model = $model->where($prefix, '>', strtotime($startTime));
  219. $model = $model->where($prefix, '<', strtotime($endTime)+86400);
  220. }
  221. break;
  222. }
  223. return $model;
  224. }
  225. /**
  226. * 获取去除html去除空格去除软回车,软换行,转换过后的字符串
  227. * @param string $str
  228. * @return string
  229. */
  230. public static function HtmlToMbStr($str){
  231. return trim(strip_tags(str_replace(["\n","\t","\r"," ","&nbsp;"],'',htmlspecialchars_decode($str))));
  232. }
  233. /**
  234. * 截取中文指定字节
  235. * @param string $str
  236. * @param int $utf8len
  237. * @param string $chaet
  238. * @param string $file
  239. * @return string
  240. */
  241. public static function getSubstrUTf8($str,$utf8len=100,$chaet='UTF-8',$file='....'){
  242. if(mb_strlen($str,$chaet)>$utf8len){
  243. $str=mb_substr($str,0,$utf8len,$chaet).$file;
  244. }
  245. return $str;
  246. }
  247. /**
  248. * 获取本季度 time
  249. * @param int|string $time
  250. * @param string $ceil
  251. * @return array
  252. */
  253. public static function getMonth($time='',$ceil=0){
  254. if($ceil!=0)
  255. $season = ceil(date('n') /3)-$ceil;
  256. else
  257. $season = ceil(date('n') /3);
  258. $firstday=date('Y-m-01',mktime(0,0,0,($season - 1) *3 +1,1,date('Y')));
  259. $lastday=date('Y-m-t',mktime(0,0,0,$season * 3,1,date('Y')));
  260. return array($firstday,$lastday);
  261. }
  262. /**
  263. * 高精度 加法
  264. * @param int|string $uid id
  265. * @param string $decField 相加的字段
  266. * @param float|int $dec 加的值
  267. * @param string $keyField id的字段
  268. * @param int $acc 精度
  269. * @return bool
  270. */
  271. public static function bcInc($key, $incField, $inc, $keyField = null, $acc=2)
  272. {
  273. if(!is_numeric($inc)) return false;
  274. $model = new self();
  275. if($keyField === null) $keyField = $model->getPk();
  276. $result = self::where($keyField,$key)->find();
  277. if(!$result) return false;
  278. $new = bcadd($result[$incField],$inc,$acc);
  279. return false !== $model->where($keyField,$key)->update([$incField=>$new]);
  280. }
  281. /**
  282. * 高精度 减法
  283. * @param int|string $uid id
  284. * @param string $decField 相减的字段
  285. * @param float|int $dec 减的值
  286. * @param string $keyField id的字段
  287. * @param bool $minus 是否可以为负数
  288. * @param int $acc 精度
  289. * @return bool
  290. */
  291. public static function bcDec($key, $decField, $dec, $keyField = null, $minus = false, $acc=2)
  292. {
  293. if(!is_numeric($dec)) 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. if(!$minus && $result[$decField] < $dec) return false;
  299. $new = bcsub($result[$decField],$dec,$acc);
  300. return false !== $model->where($keyField,$key)->update([$decField=>$new]);
  301. }
  302. /**
  303. * @param null $model
  304. * @return Model
  305. */
  306. protected static function getSelfModel($model = null)
  307. {
  308. return $model == null ? (new self()) : $model;
  309. }
  310. }