DB.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. <?php
  2. class DB
  3. {
  4. /**
  5. * 批量插入
  6. *
  7. * @param $table
  8. * @param array $data
  9. * @param array $header 可以不传 但 $data 必须是关联数组集合
  10. * @return int
  11. * @throws CDbException
  12. */
  13. public static function safeBatchInsert($table, array $data, array $header = [])
  14. {
  15. $params = [];
  16. if (!$data) {
  17. return false;
  18. }
  19. if (!$header) {
  20. $header = array_keys($data[0]);
  21. }
  22. $table = self::formTableName($table);
  23. $headerStr = implode(',', $header);
  24. $sql = "INSERT INTO {$table} ({$headerStr}) values ";
  25. foreach ($data as $k => $datum) {
  26. $tempValues = [];
  27. $i = 0;
  28. foreach ($datum as $ik => $item) {
  29. $paramKey = ':'.$header[$i].$k;
  30. $paramValue = is_numeric($item) ? $item : "{$item}";
  31. $params[$paramKey] = $paramValue;
  32. $tempValues[] = $paramKey;
  33. $i++;
  34. }
  35. $valueStr = implode(',', $tempValues);
  36. $sql .= "({$valueStr}),";
  37. }
  38. return Yii::app()->db->createCommand(rtrim($sql, ','))->execute($params);
  39. }
  40. /**
  41. * 获取sql操作command对象
  42. *
  43. * @param string $dbName
  44. * @return \CDbCommand
  45. */
  46. public static function getDbCommand($dbName = 'db')
  47. {
  48. $command = \Yii::app()->$dbName->createCommand();
  49. $command->reset();
  50. return $command;
  51. }
  52. /**
  53. * 从数据库获取数据的通用方法
  54. *
  55. * @param string $tableName 表名
  56. * @param array $filters 筛选条件
  57. * @param string $fields 字段
  58. * @param string $group
  59. * @param string $order
  60. * @param integer $page 分页,如果为0,就不分页
  61. * @param integer $pageSize
  62. * @param string $index 强制指定的索引
  63. * @param string $dbName 数据库名
  64. * @return array
  65. */
  66. public static function getDataByCondition(
  67. $tableName,
  68. $filters,
  69. $fields = '*',
  70. $group = '',
  71. $order = '',
  72. $page = 0,
  73. $pageSize = 0,
  74. $index = '',
  75. $dbName = 'db'
  76. ): array {
  77. $db = self::getDbCommand($dbName);
  78. if (!empty($index)) {
  79. $tableName .= " FORCE INDEX (`{$index}`)";
  80. }
  81. $criteria = new \CDbCriteria();
  82. if (!empty($filters)) {
  83. foreach ($filters as $key => $value) {
  84. if (is_array($value) && 'like' === reset($value)) {
  85. $criteria->compare($key, array_pop($value), true);
  86. } elseif (is_array($value) && 'condition' === reset($value)) {
  87. $criteria->addCondition(array_pop($value));
  88. } elseif (is_array($value) && 'betweenCondition' === reset($value)) {
  89. $criteria->addBetweenCondition($key, $value[1], $value[2]);
  90. } elseif (is_array($value) && $value === array()) {
  91. $criteria->addInCondition($key, $value);
  92. } elseif (empty($value)) {
  93. $criteria->addCondition("{$key} = :{$key}");
  94. $criteria->params[':'.$key] = $value;
  95. } else {
  96. $criteria->compare($key, $value);
  97. }
  98. }
  99. }
  100. $build = $db->select($fields)
  101. ->from($tableName)
  102. ->where($criteria->condition, $criteria->params);
  103. !empty($group) && $build->group($group);
  104. !empty($order) && $build->order($order);
  105. if ($page > 0) {
  106. $page = intval($page);
  107. $pageSize = intval($pageSize);
  108. $offset = $pageSize * ($page - 1);
  109. $build->limit($pageSize, $offset);
  110. }
  111. /* if ($isLock) {
  112. $sql = $build->getText() . " FOR UPDATE";
  113. return $this->queryAllBySql($sql, $build->params);
  114. } */
  115. return $build->queryAll();
  116. }
  117. public static function updateById($tableName, $info, $id)
  118. {
  119. $id = intval($id);
  120. if ($id <= 0 || empty($info)) {
  121. return false;
  122. }
  123. $info['update_date'] = date('Y-m-d H:i:s');
  124. $db = self::getDbCommand();
  125. return $db->update(self::formTableName($tableName), $info, "id=:id", [':id' => $id]);
  126. }
  127. public static function getInfoById($tableName, $id, $fields = '*')
  128. {
  129. $id = intval($id);
  130. if ($id <= 0) {
  131. return [];
  132. }
  133. return self::getInfoWithCriteria($tableName, DbCriteria::simpleCompare(['id' => $id])->setSelect($fields));
  134. }
  135. public static function deleteById($tableName, $id)
  136. {
  137. $id = intval($id);
  138. if ($id <= 0) {
  139. return false;
  140. }
  141. $db = self::getDbCommand();
  142. return $db->delete(self::formTableName($tableName), "id=:id", [':id' => $id]);
  143. }
  144. public static function formTableName($tableName)
  145. {
  146. return 'wx_' . str_replace('wx_', '', $tableName);
  147. }
  148. /**
  149. * 从数据库获取数据的通用方法,与上面的方法相比,就是多了分页的内容
  150. *
  151. * @param string $tableName 表名
  152. * @param array $filters 筛选条件
  153. * @param string $fields 字段
  154. * @param string $group
  155. * @param string $order
  156. * @param integer $page 分页,如果为0,就不分页
  157. * @param integer $pageSize
  158. * @param string $index 强制指定的索引
  159. * @param string $dbName 数据库名
  160. * @return array
  161. */
  162. public static function getWebDataByCondition(
  163. $tableName,
  164. $filters,
  165. $fields = '*',
  166. $group = '',
  167. $order = '',
  168. $page = 0,
  169. $pageSize = 0,
  170. $index = '',
  171. $dbName = 'db'
  172. ) {
  173. $return = [
  174. 'page' => $page,
  175. 'pageSize' => $pageSize,
  176. 'totalPage' => -1,
  177. 'counts' => -1,
  178. 'records' => [],
  179. ];
  180. $db = self::getDbCommand($dbName);
  181. if (!empty($index)) {
  182. $tableName .= " FORCE INDEX (`{$index}`)";
  183. }
  184. $criteria = new \CDbCriteria();
  185. if (!empty($filters)) {
  186. foreach ($filters as $key => $value) {
  187. if (is_array($value) && 'like' === reset($value)) {
  188. $criteria->compare($key, array_pop($value), true);
  189. } elseif (is_array($value) && 'condition' === reset($value)) {
  190. $criteria->addCondition(array_pop($value));
  191. } elseif (is_array($value) && 'betweenCondition' === reset($value)) {
  192. $criteria->addBetweenCondition($key, $value[1], $value[2]);
  193. } elseif (is_array($value) && $value === array()) {
  194. $criteria->addInCondition($key, $value);
  195. } elseif (empty($value)) {
  196. $criteria->addCondition("{$key} = :{$key}");
  197. $criteria->params[':'.$key] = $value;
  198. } else {
  199. $criteria->compare($key, $value);
  200. }
  201. }
  202. }
  203. // 如果有分页,则查询总记录数
  204. $counts = -1;
  205. if ($page > 0) {
  206. if (empty($group)) {
  207. $counts = $db->select("count(*) as total")
  208. ->from($tableName)
  209. ->where($criteria->condition, $criteria->params)
  210. ->queryScalar();
  211. $db->reset();
  212. } else {
  213. $count_data = $db->select("{$group}")
  214. ->from($tableName)
  215. ->where($criteria->condition, $criteria->params)
  216. ->group($group)
  217. ->queryAll();
  218. $db->reset();
  219. $counts = count($count_data);
  220. }
  221. $counts = intval($counts);
  222. if ($counts < 1) {
  223. return $return; // 数据为空
  224. }
  225. }
  226. $build = $db->select($fields)
  227. ->from($tableName)
  228. ->where($criteria->condition, $criteria->params);
  229. !empty($group) && $build->group($group);
  230. !empty($order) && $build->order($order);
  231. // 如果有分页,则对查询条件做处理
  232. $totalPages = -1;
  233. if ($pageSize > 0) {
  234. //计算总页数
  235. $totalPages = ceil($counts / $pageSize);
  236. $offset = $pageSize * ($page - 1);
  237. $build->limit($pageSize, $offset);
  238. $return['totalPage'] = $totalPages;
  239. $return['counts'] = $counts;
  240. }
  241. $return['records'] = $build->queryAll();
  242. return $return;
  243. }
  244. /**
  245. * 从数据库获取数据的通用方法,只获取一条数据
  246. *
  247. * @param string $tableName 表名
  248. * @param array $filters 筛选条件
  249. * @param string $fields 字段
  250. * @param string $group
  251. * @param string $order
  252. * @param integer $page 分页,如果为0,就不分页
  253. * @param integer $pageSize
  254. * @param string $index 强制指定的索引
  255. * @param string $dbName 数据库名
  256. * @return array
  257. */
  258. public static function getOneByCondition(
  259. $tableName,
  260. $filters,
  261. $fields = '*',
  262. $group = '',
  263. $index = '',
  264. $dbName = 'db'
  265. ) {
  266. $data = self::getDataByCondition($tableName, $filters, $fields, $group, '', 0, 0, $index, $dbName);
  267. return !empty($data) ? reset($data) : [];
  268. }
  269. /**
  270. * 向数据库插入数据
  271. *
  272. * @param string $tableName 表名
  273. * @param array $info
  274. * @param string $dbName
  275. * @return int
  276. */
  277. public static function addData($tableName, $info, $dbName = 'db')
  278. {
  279. if (empty($info)) {
  280. return false;
  281. }
  282. $command = self::getDbCommand($dbName);
  283. $ret = $command->insert(self::formTableName($tableName), $info);
  284. if ($ret) {
  285. return $command->getConnection()->getLastInsertID();
  286. }
  287. return false;
  288. }
  289. /**
  290. * 根据条件删除数据库内容
  291. *
  292. * @param string $tableName
  293. * @param array $filters
  294. * @param string $dbName
  295. * @return int
  296. */
  297. public static function deleteByCondition($tableName, $filters, $dbName = 'db')
  298. {
  299. $tableName = self::formTableName($tableName);
  300. if (empty($filters)) {
  301. return false;
  302. }
  303. $command = self::getDbCommand($dbName);
  304. $condition = '';
  305. $params = [];
  306. foreach ($filters as $key => $value) {
  307. $condition .= " {$key}=:{$key} AND";
  308. $params[':'.$key] = $value;
  309. }
  310. $condition = trim($condition, 'AND');
  311. $condition = trim($condition);
  312. return $command->delete($tableName, $condition, $params);
  313. }
  314. /**
  315. * 获取model的错误信息
  316. *
  317. * @param object $model
  318. * @return string
  319. */
  320. public static function getModelErrorMsg($model)
  321. {
  322. $str = '';
  323. if ($model->hasErrors()) {
  324. $errors = [];
  325. foreach ($model->getErrors() as $error) {
  326. $errors += $error;
  327. }
  328. $str = implode("<br/>", $errors);
  329. }
  330. return $str;
  331. }
  332. /**
  333. * 通过 DbCriteria 来搜索
  334. * @param string $table_name 表名
  335. * @param DbCriteria $criteria 分页通过 setPage 设置,否则不会查询分页信息
  336. * @return array|\CDbDataReader 格式: ['current'=>1, 'size'=>1, 'totalPage'=>1, 'total'=>1, 'records'=>[]]
  337. * @throws \CException
  338. */
  339. public static function getListWithCriteria(string $table_name, DbCriteria $criteria)
  340. {
  341. // 数据返回格式
  342. $retData = [
  343. 'current' => $criteria->getPage(),
  344. 'size' => $criteria->getPageSize(),
  345. 'totalPage' => 0,
  346. 'total' => 0,
  347. 'records' => [],
  348. ];
  349. $table_name = self::formTableName($table_name);
  350. if ($criteria->alias) {
  351. $table_name .= ' as '.$criteria->alias;
  352. }
  353. // 指定索引
  354. if (!empty($criteria->forceIndex)) {
  355. $table_name .= " FORCE INDEX (`{$criteria->forceIndex}`)";
  356. }
  357. // 根据 DbCriteria 构建查询
  358. $build = self::getDbCommand()->select($criteria->select)
  359. ->from($table_name)
  360. ->where($criteria->condition, $criteria->params);
  361. !empty($criteria->group) && $build->group($criteria->group);
  362. !empty($criteria->having) && $build->having($criteria->having);
  363. !empty($criteria->join) && $build->setJoin($criteria->join);
  364. // 有分页需要先查询总数 然后再恢复 builder
  365. if ($criteria->isFenye()) {
  366. if (!empty($criteria->group)) {
  367. // 使用group以后 需要子查询来统计总条数
  368. $subQuery = $build->select($criteria->getCountSelectStr())->getText();
  369. $totalNum = self::getDbCommand()->select('count(*)')->from("($subQuery) t")->queryScalar(
  370. $criteria->params
  371. );
  372. } else {
  373. $totalNum = $build->select($criteria->getCountSelectStr())->queryScalar();
  374. }
  375. $retData['total'] = $totalNum;
  376. $retData['totalPage'] = ceil($totalNum / $criteria->getPageSize());
  377. $build = self::getDbCommand()->select($criteria->select)
  378. ->from($table_name)
  379. ->where($criteria->condition, $criteria->params);
  380. !empty($criteria->group) && $build->group($criteria->group);
  381. !empty($criteria->having) && $build->having($criteria->having);
  382. !empty($criteria->join) && $build->setJoin($criteria->join);
  383. $build->limit($criteria->limit, $criteria->offset);
  384. } elseif ($criteria->limit > 0) {
  385. // 不做分页 单纯控制偏移及数量
  386. $build->limit($criteria->limit, $criteria->offset);
  387. }
  388. !empty($criteria->order) && $build->order($criteria->order);
  389. $retData['records'] = $build->queryAll() ?: [];
  390. // debug
  391. if ($criteria->getDebugMode() || LWM_ENV != 'prod') {
  392. Logger::info(
  393. json_encode(
  394. [
  395. 'DbCriteriaDebug' => $criteria->getSql($build->getText(), $criteria->params),
  396. 'tag' => $criteria->getDebugTag(),
  397. ],
  398. JSON_UNESCAPED_UNICODE
  399. )
  400. );
  401. }
  402. return $retData;
  403. }
  404. /**
  405. * 通过 DbCriteria 来搜索
  406. * @param string $table_name 表名
  407. * @param DbCriteria $criteria
  408. * @return array|\CDbDataReader
  409. * @throws \CException
  410. */
  411. public static function getInfoWithCriteria(string $table_name, DbCriteria $criteria)
  412. {
  413. $table_name = self::formTableName($table_name);
  414. // 指定索引
  415. if (!empty($criteria->forceIndex)) {
  416. $table_name .= " FORCE INDEX (`{$criteria->forceIndex}`)";
  417. }
  418. // 根据 DbCriteria 构建查询
  419. $build = self::getDbCommand()->select($criteria->select)
  420. ->from($table_name)
  421. ->limit(1)
  422. ->where($criteria->condition, $criteria->params);
  423. !empty($criteria->group) && $build->group($criteria->group);
  424. !empty($criteria->having) && $build->having($criteria->having);
  425. !empty($criteria->order) && $build->order($criteria->order);
  426. // debug
  427. if ($criteria->getDebugMode() || LWM_ENV != 'prod') {
  428. Logger::info(
  429. json_encode(
  430. [
  431. 'DbCriteriaDebug' => $criteria->getSql($build->getText(), $criteria->params),
  432. 'tag' => $criteria->getDebugTag(),
  433. ],
  434. JSON_UNESCAPED_UNICODE
  435. )
  436. );
  437. }
  438. return $build->queryRow();
  439. }
  440. public static function getScalerWithCriteria(string $table_name, DbCriteria $criteria)
  441. {
  442. $data = self::getInfoWithCriteria($table_name, $criteria);
  443. return $data ? reset($data) : '';
  444. }
  445. }