DB.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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 formTableName($tableName)
  155. {
  156. return 'wx_' . trim($tableName, 'wx_');
  157. }
  158. /**
  159. * 从数据库获取数据的通用方法,与上面的方法相比,就是多了分页的内容
  160. *
  161. * @param string $tableName 表名
  162. * @param array $filters 筛选条件
  163. * @param string $fields 字段
  164. * @param string $group
  165. * @param string $order
  166. * @param integer $page 分页,如果为0,就不分页
  167. * @param integer $pageSize
  168. * @param string $index 强制指定的索引
  169. * @param string $dbName 数据库名
  170. * @return array
  171. */
  172. public static function getWebDataByCondition(
  173. $tableName,
  174. $filters,
  175. $fields = '*',
  176. $group = '',
  177. $order = '',
  178. $page = 0,
  179. $pageSize = 0,
  180. $index = '',
  181. $dbName = 'db'
  182. ) {
  183. $return = [
  184. 'page' => $page,
  185. 'pageSize' => $pageSize,
  186. 'totalPage' => -1,
  187. 'counts' => -1,
  188. 'records' => [],
  189. ];
  190. $db = self::getDbCommand($dbName);
  191. if (!empty($index)) {
  192. $tableName .= " FORCE INDEX (`{$index}`)";
  193. }
  194. $criteria = new \CDbCriteria();
  195. if (!empty($filters)) {
  196. foreach ($filters as $key => $value) {
  197. if (is_array($value) && 'like' === reset($value)) {
  198. $criteria->compare($key, array_pop($value), true);
  199. } elseif (is_array($value) && 'condition' === reset($value)) {
  200. $criteria->addCondition(array_pop($value));
  201. } elseif (is_array($value) && 'betweenCondition' === reset($value)) {
  202. $criteria->addBetweenCondition($key, $value[1], $value[2]);
  203. } elseif (is_array($value) && $value === array()) {
  204. $criteria->addInCondition($key, $value);
  205. } elseif (empty($value)) {
  206. $criteria->addCondition("{$key} = :{$key}");
  207. $criteria->params[':'.$key] = $value;
  208. } else {
  209. $criteria->compare($key, $value);
  210. }
  211. }
  212. }
  213. // 如果有分页,则查询总记录数
  214. $counts = -1;
  215. if ($page > 0) {
  216. if (empty($group)) {
  217. $counts = $db->select("count(*) as total")
  218. ->from($tableName)
  219. ->where($criteria->condition, $criteria->params)
  220. ->queryScalar();
  221. $db->reset();
  222. } else {
  223. $count_data = $db->select("{$group}")
  224. ->from($tableName)
  225. ->where($criteria->condition, $criteria->params)
  226. ->group($group)
  227. ->queryAll();
  228. $db->reset();
  229. $counts = count($count_data);
  230. }
  231. $counts = intval($counts);
  232. if ($counts < 1) {
  233. return $return; // 数据为空
  234. }
  235. }
  236. $build = $db->select($fields)
  237. ->from($tableName)
  238. ->where($criteria->condition, $criteria->params);
  239. !empty($group) && $build->group($group);
  240. !empty($order) && $build->order($order);
  241. // 如果有分页,则对查询条件做处理
  242. $totalPages = -1;
  243. if ($pageSize > 0) {
  244. //计算总页数
  245. $totalPages = ceil($counts / $pageSize);
  246. $offset = $pageSize * ($page - 1);
  247. $build->limit($pageSize, $offset);
  248. $return['totalPage'] = $totalPages;
  249. $return['counts'] = $counts;
  250. }
  251. $return['records'] = $build->queryAll();
  252. return $return;
  253. }
  254. /**
  255. * 从数据库获取数据的通用方法,只获取一条数据
  256. *
  257. * @param string $tableName 表名
  258. * @param array $filters 筛选条件
  259. * @param string $fields 字段
  260. * @param string $group
  261. * @param string $order
  262. * @param integer $page 分页,如果为0,就不分页
  263. * @param integer $pageSize
  264. * @param string $index 强制指定的索引
  265. * @param string $dbName 数据库名
  266. * @return array
  267. */
  268. public static function getOneByCondition(
  269. $tableName,
  270. $filters,
  271. $fields = '*',
  272. $group = '',
  273. $index = '',
  274. $dbName = 'db'
  275. ) {
  276. $data = self::getDataByCondition($tableName, $filters, $fields, $group, '', 0, 0, $index, $dbName);
  277. return !empty($data) ? reset($data) : [];
  278. }
  279. /**
  280. * 向数据库插入数据
  281. *
  282. * @param string $tableName 表名
  283. * @param array $info
  284. * @param string $dbName
  285. * @return int
  286. */
  287. public static function addData($tableName, $info, $dbName = 'db')
  288. {
  289. if (empty($info)) {
  290. return false;
  291. }
  292. $command = self::getDbCommand($dbName);
  293. $ret = $command->insert(self::formTableName($tableName), $info);
  294. if ($ret) {
  295. return $command->getConnection()->getLastInsertID();
  296. }
  297. return false;
  298. }
  299. /**
  300. * 根据条件删除数据库内容
  301. *
  302. * @param string $tableName
  303. * @param array $filters
  304. * @param string $dbName
  305. * @return int
  306. */
  307. public static function deleteByCondition($tableName, $filters, $dbName = 'db')
  308. {
  309. if (empty($filters)) {
  310. return false;
  311. }
  312. $command = self::getDbCommand($dbName);
  313. $condition = '';
  314. $params = [];
  315. foreach ($filters as $key => $value) {
  316. $condition .= " {$key}=:{$key} AND";
  317. $params[':'.$key] = $value;
  318. }
  319. $condition = trim($condition, 'AND');
  320. $condition = trim($condition);
  321. return $command->delete($tableName, $condition, $params);
  322. }
  323. /**
  324. * 获取model的错误信息
  325. *
  326. * @param object $model
  327. * @return string
  328. */
  329. public static function getModelErrorMsg($model)
  330. {
  331. $str = '';
  332. if ($model->hasErrors()) {
  333. $errors = [];
  334. foreach ($model->getErrors() as $error) {
  335. $errors += $error;
  336. }
  337. $str = implode("<br/>", $errors);
  338. }
  339. return $str;
  340. }
  341. /**
  342. * 通过 DbCriteria 来搜索
  343. * @param string $table_name 表名
  344. * @param DbCriteria $criteria 分页通过 setPage 设置,否则不会查询分页信息
  345. * @return array|\CDbDataReader 格式: ['page'=>1, 'pageSize'=>1, 'totalPage'=>1, 'counts'=>1, 'records'=>[]]
  346. * @throws \CException
  347. */
  348. public static function getListWithCriteria(string $table_name, DbCriteria $criteria)
  349. {
  350. // 数据返回格式
  351. $retData = [
  352. 'current' => $criteria->getPage(),
  353. 'size' => $criteria->getPageSize(),
  354. 'totalPage' => 0,
  355. 'total' => 0,
  356. 'records' => [],
  357. ];
  358. $table_name = self::formTableName($table_name);
  359. if ($criteria->alias) {
  360. $table_name .= ' as '.$criteria->alias;
  361. }
  362. // 指定索引
  363. if (!empty($criteria->forceIndex)) {
  364. $table_name .= " FORCE INDEX (`{$criteria->forceIndex}`)";
  365. }
  366. // 根据 DbCriteria 构建查询
  367. $build = self::getDbCommand()->select($criteria->select)
  368. ->from($table_name)
  369. ->where($criteria->condition, $criteria->params);
  370. !empty($criteria->group) && $build->group($criteria->group);
  371. !empty($criteria->having) && $build->having($criteria->having);
  372. !empty($criteria->join) && $build->setJoin($criteria->join);
  373. // 有分页需要先查询总数 然后再恢复 builder
  374. if ($criteria->isFenye()) {
  375. if (!empty($criteria->group)) {
  376. // 使用group以后 需要子查询来统计总条数
  377. $subQuery = $build->select($criteria->getCountSelectStr())->getText();
  378. $totalNum = self::getDbCommand()->select('count(*)')->from("($subQuery) t")->queryScalar(
  379. $criteria->params
  380. );
  381. } else {
  382. $totalNum = $build->select($criteria->getCountSelectStr())->queryScalar();
  383. }
  384. $retData['total'] = $totalNum;
  385. $retData['totalPage'] = ceil($totalNum / $criteria->getPageSize());
  386. $build = self::getDbCommand()->select($criteria->select)
  387. ->from($table_name)
  388. ->where($criteria->condition, $criteria->params);
  389. !empty($criteria->group) && $build->group($criteria->group);
  390. !empty($criteria->having) && $build->having($criteria->having);
  391. !empty($criteria->join) && $build->setJoin($criteria->join);
  392. $build->limit($criteria->limit, $criteria->offset);
  393. } elseif ($criteria->limit > 0) {
  394. // 不做分页 单纯控制偏移及数量
  395. $build->limit($criteria->limit, $criteria->offset);
  396. }
  397. !empty($criteria->order) && $build->order($criteria->order);
  398. $retData['records'] = $build->queryAll() ?: [];
  399. // debug
  400. if ($criteria->getDebugMode()) {
  401. Logger::info(
  402. json_encode(
  403. [
  404. 'DbCriteriaDebug' => $criteria->getSql($build->getText(), $criteria->params),
  405. 'tag' => $criteria->getDebugTag(),
  406. ],
  407. JSON_UNESCAPED_UNICODE
  408. )
  409. );
  410. }
  411. return $retData;
  412. }
  413. /**
  414. * 通过 DbCriteria 来搜索
  415. * @param string $table_name 表名
  416. * @param DbCriteria $criteria
  417. * @return array|\CDbDataReader
  418. * @throws \CException
  419. */
  420. public static function getInfoWithCriteria(string $table_name, DbCriteria $criteria)
  421. {
  422. $table_name = self::formTableName($table_name);
  423. // 指定索引
  424. if (!empty($criteria->forceIndex)) {
  425. $table_name .= " FORCE INDEX (`{$criteria->forceIndex}`)";
  426. }
  427. // 根据 DbCriteria 构建查询
  428. $build = self::getDbCommand()->select($criteria->select)
  429. ->from($table_name)
  430. ->limit(1)
  431. ->where($criteria->condition, $criteria->params);
  432. !empty($criteria->group) && $build->group($criteria->group);
  433. !empty($criteria->having) && $build->having($criteria->having);
  434. !empty($criteria->order) && $build->order($criteria->order);
  435. // debug
  436. if ($criteria->getDebugMode()) {
  437. Logger::info(
  438. json_encode(
  439. [
  440. 'DbCriteriaDebug' => $criteria->getSql($build->getText(), $criteria->params),
  441. 'tag' => $criteria->getDebugTag(),
  442. ],
  443. JSON_UNESCAPED_UNICODE
  444. )
  445. );
  446. }
  447. return $build->queryRow();
  448. }
  449. public static function getScalerWithCriteria(string $table_name, DbCriteria $criteria)
  450. {
  451. $data = self::getInfoWithCriteria($table_name, $criteria);
  452. return $data ? reset($data) : '';
  453. }
  454. }