DB.php 16 KB

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