Base.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. <?php
  2. namespace common\base\models;
  3. use common\components\util;
  4. use yii\db\ActiveRecord;
  5. class Base extends ActiveRecord
  6. {
  7. /**
  8. * 获取当前模型实例
  9. * @return static
  10. */
  11. public function getModel()
  12. {
  13. $self = get_called_class();
  14. return new $self;
  15. }
  16. /**
  17. * 添加数据
  18. * @param array $data 数据数组
  19. * @param bool $returnObject 是否返回对象,true返回模型对象,false返回数组
  20. * @return $this|array
  21. * @throws \Exception
  22. */
  23. public function add($data, $returnObject = false)
  24. {
  25. $model = $this->getModel();
  26. $attributes = $model->attributes;
  27. $fields = array_keys($attributes);
  28. foreach ($fields as $key) {
  29. if (isset($data[$key])) {
  30. $model->$key = $data[$key];
  31. }
  32. }
  33. if (!$model->validate()) {
  34. // 验证失败: $errors 是一个包含错误信息的数组
  35. \Yii::error(static::tableName() . ' -- model validate errors: ' . json_encode($model->errors));
  36. util::fail('输入数据验证失败');
  37. }
  38. // 保存数据并检查结果
  39. if (!$model->save()) {
  40. $errors = $model->errors;
  41. \Yii::error(static::tableName() . ' -- save failed: ' . json_encode($errors));
  42. throw new \Exception('数据保存失败: ' . json_encode($errors));
  43. }
  44. return $returnObject ? $model : $model->attributes;
  45. }
  46. /**
  47. * 批量添加
  48. * @param array $data 二维数组 [['name'=>'a'], ['name'=>'b']]
  49. * @return void
  50. */
  51. public function batchAdd($data)
  52. {
  53. $model = $this->getModel();
  54. foreach ($data as $attributes) {
  55. $newModel = clone $model;
  56. // false 不检测字段安全 true 需要在model设置rules
  57. $newModel->setAttributes($attributes, false);
  58. $newModel->save();
  59. }
  60. }
  61. /**
  62. * 获取表的所有字段名
  63. * @return array
  64. */
  65. public function getFields()
  66. {
  67. $model = $this->getModel();
  68. $attributes = $model->attributes;
  69. return array_keys($attributes);
  70. }
  71. /**
  72. * 根据主键ID删除一条记录
  73. * @param int|string $id 主键ID
  74. * @return int|false 删除的行数,失败返回false
  75. * @throws \Throwable
  76. * @throws \yii\db\StaleObjectException
  77. */
  78. public function deleteById($id)
  79. {
  80. $model = $this->getModel();
  81. return $model::findOne($id)->delete();
  82. }
  83. /**
  84. * 根据多个主键ID批量删除
  85. * @param array $ids 主键ID数组
  86. * @return int 删除的行数
  87. */
  88. public function deleteByIds($ids)
  89. {
  90. $model = $this->getModel();
  91. return $model::deleteAll(['id' => $ids]);
  92. }
  93. /**
  94. * 根据条件删除一条或多条记录
  95. * @param array $condition 查询条件
  96. * @return int 删除的行数
  97. */
  98. public function deleteByCondition($condition)
  99. {
  100. if (empty($condition)) {
  101. return 0;
  102. }
  103. $where = array();
  104. $variable = array();
  105. foreach ($condition as $key => $val) {
  106. $where[] = $key . '=:' . $key;
  107. $variable[':' . $key] = $val;
  108. }
  109. $whereString = implode(' and ', $where);
  110. $count = self::deleteAll($whereString, $variable);
  111. return $count;
  112. }
  113. /**
  114. * 根据主键ID更新一条记录
  115. * @param int|string $id 主键ID
  116. * @param array $data 更新的数据
  117. * @return array ['status' => bool, 'data' => array] status=true更新成功,false更新失败
  118. */
  119. public function updateById($id, $data)
  120. {
  121. $model = $this->getModel();
  122. $attributes = $model->attributes;
  123. $fields = array_keys($attributes);
  124. foreach ($data as $key => $val) {
  125. if (in_array($key, $fields) == false) {
  126. //删除表里不存在字段
  127. unset($data[$key]);
  128. }
  129. }
  130. $re = self::updateAll($data, 'id=:id', ['id' => $id]);
  131. if ($re == 1) {
  132. return ['status' => true, 'data' => $data];
  133. }
  134. return ['status' => false, 'data' => $data];
  135. }
  136. /**
  137. * 根据多个主键ID批量更新
  138. * @param array $ids 主键ID数组
  139. * @param array $data 更新的数据
  140. * @return int 更新的行数
  141. */
  142. public function updateByIds($ids, $data)
  143. {
  144. return self::updateAll($data, ['id' => $ids]);
  145. }
  146. /**
  147. * 根据条件更新一条或多条记录
  148. * @param array $condition 查询条件
  149. * @param array $data 更新的数据
  150. * @return int 更新的行数
  151. */
  152. public function updateByCondition($condition, $data)
  153. {
  154. $where = array();
  155. $variable = array();
  156. foreach ($condition as $key => $val) {
  157. $where[] = $key . '=:' . $key;
  158. $variable[':' . $key] = $val;
  159. }
  160. $whereString = implode(' and ', $where);
  161. $count = self::updateAll($data, $whereString, $variable);
  162. return $count;
  163. }
  164. /**
  165. * 根据主键ID查出一条记录
  166. * @param int|string $id 主键ID
  167. * @param bool $returnObject 是否返回对象
  168. * @param string|array $field 查询字段
  169. * @return array|ActiveRecord|null
  170. * @throws \Exception
  171. */
  172. public function getById($id, $returnObject = false, $field = '*')
  173. {
  174. $query = $this->conditionQuery(['id' => $id])->select($field);
  175. if ($returnObject == false) {
  176. return $query->asArray()->one();
  177. } else {
  178. return $query->one();
  179. }
  180. }
  181. /**
  182. * 根据条件查出一条记录
  183. * @param array $condition 查询条件
  184. * @param bool $returnObject 是否返回对象
  185. * @param string|array|bool $order 排序
  186. * @param string|array $field 查询字段
  187. * @return array|ActiveRecord|null
  188. * @throws \Exception
  189. */
  190. public function getByCondition($condition, $returnObject = false, $order = false, $field = '*')
  191. {
  192. $query = $this->conditionQuery($condition)->select($field);
  193. if (isset($order)) {
  194. $query->orderBy($order);
  195. }
  196. return $returnObject == true ? $query->one() : $query->asArray()->one();
  197. }
  198. /**
  199. * 获取第一条记录 (通常用于获取任意一条或结合排序获取特定一条)
  200. * @param bool $returnObject 是否返回对象
  201. * @param string|array|bool $order 排序
  202. * @param string|array $field 查询字段
  203. * @return array|ActiveRecord|null
  204. * @throws \Exception
  205. */
  206. public function getOne($returnObject = false, $order = false, $field = '*')
  207. {
  208. $query = $this->conditionQuery([])->select($field);
  209. if (isset($order)) {
  210. $query->orderBy($order);
  211. }
  212. return $returnObject == true ? $query->one() : $query->asArray()->one();
  213. }
  214. /**
  215. * 构建查询条件对象
  216. * 支持查询条件包括:
  217. * $condition = [
  218. * 'name' => 'john', // 等于
  219. * 'id>' => 3, // 大于
  220. * 'id<' => 10, // 小于
  221. * 'id!=' => -1, // 不等于
  222. * 'id' => ['in', [10,11,12]], // IN
  223. * 'id' => ['not in', [10,11,12]], // NOT IN
  224. * 'age' => ['between', [20,30]], // BETWEEN
  225. * 'name' => ['like', 'Jack'] // LIKE
  226. * ];
  227. * @param array $condition 查询条件数组
  228. * @return \yii\db\ActiveQuery
  229. * @throws \Exception
  230. */
  231. public function conditionQuery($condition = [])
  232. {
  233. $whereNum = 0;
  234. $query = self::find();
  235. if (!empty($condition)) {
  236. foreach ($condition as $key => $val) {
  237. $param = [$key => $val];
  238. if (strstr($key, '!=')) {
  239. //不等于
  240. $pos = strpos($key, '!=');
  241. $currentKey = substr($key, 0, $pos);
  242. $param = ['!=', $currentKey, $val];
  243. } elseif (strstr($key, '>')) {
  244. //暂不支持大于等于,等于请使用between
  245. $pos = strpos($key, '>');
  246. $currentKey = substr($key, 0, $pos);
  247. $param = ['>', $currentKey, $val];
  248. } elseif (strstr($key, '<')) {
  249. //暂不支持小于等于,等于请使用between
  250. $pos = strpos($key, '<');
  251. $currentKey = substr($key, 0, $pos);
  252. $param = ['<', $currentKey, $val];
  253. } elseif (is_array($val)) {
  254. if (count($val) != 2) {
  255. util::fail('参数不至2个,非法查询方式:' . json_encode($condition));
  256. }
  257. if ($val[0] == 'in') {
  258. $param = ['in', $key, $val[1]];
  259. } elseif ($val[0] == 'not in') {
  260. $param = ['not in', $key, $val[1]];
  261. } elseif ($val[0] == 'between') {
  262. $param = ['between', $key, $val[1][0], $val[1][1]];
  263. } elseif ($val[0] == 'like') {
  264. $param = ['like', $key, $val[1]];
  265. } else {
  266. util::fail('非法查询方式:' . json_encode($condition));
  267. }
  268. } else {
  269. }
  270. if ($whereNum == 0) {
  271. $query->where($param);
  272. } else {
  273. $query->andWhere($param);
  274. }
  275. $whereNum++;
  276. }
  277. }
  278. return $query;
  279. }
  280. /**
  281. * 判断数据是否存在
  282. * @param array $condition 查询条件
  283. * @return bool
  284. * @throws \Exception
  285. */
  286. public function exists($condition)
  287. {
  288. return $this->conditionQuery($condition)->exists();
  289. }
  290. /**
  291. * 根据条件查出多条记录
  292. * @param array $condition 查询条件
  293. * @param string|array|null $order 排序
  294. * @param string|array $field 查询字段
  295. * @param string|callable|null $indexBy 索引字段
  296. * @param bool $returnObject 是否返回对象
  297. * @return array|ActiveRecord[]
  298. * @throws \Exception
  299. */
  300. public function getAllByCondition($condition, $order = null, $field, $indexBy = null, $returnObject = false)
  301. {
  302. $query = $this->conditionQuery($condition)->select($field);
  303. if (isset($indexBy)) {
  304. $query->indexBy($indexBy);
  305. }
  306. if (isset($order)) {
  307. $query->orderBy($order);
  308. }
  309. if ($returnObject == false) {
  310. return $query->asArray()->all();
  311. } else {
  312. return $query->all();
  313. }
  314. }
  315. /**
  316. * 根据多个主键ID查询多条记录
  317. * @param array $ids 主键ID数组
  318. * @param string|array|null $order 排序
  319. * @param string|callable|null $indexBy 索引字段
  320. * @param string|array $field 查询字段
  321. * @return array
  322. * @throws \Exception
  323. */
  324. public function getByIds($ids, $order = null, $indexBy = null, $field = '*')
  325. {
  326. $data = [];
  327. if (empty($ids)) {
  328. return $data;
  329. }
  330. $query = $this->conditionQuery(['id' => ['in', $ids]])->select($field);
  331. if (isset($indexBy)) {
  332. $query->indexBy($indexBy);
  333. }
  334. if (!empty($order)) {
  335. $query->order($order);
  336. }
  337. $data = $query->asArray()->all();
  338. return $data;
  339. }
  340. /**
  341. * 根据条件获取记录数量
  342. * @param array $condition 查询条件
  343. * @return int|string
  344. * @throws \Exception
  345. */
  346. public function getCount($condition)
  347. {
  348. return $this->conditionQuery($condition)->count();
  349. }
  350. /**
  351. * 分页查询列表
  352. * @param string|array $field 查询字段
  353. * @param array $where 查询条件
  354. * @param int $page 当前页码
  355. * @param int $pageSize 每页数量
  356. * @param string|array $order 排序
  357. * @param string|array $with 关联查询
  358. * @return array ['totalNum' => int, 'totalPage' => int, 'moreData' => int, 'list' => array]
  359. * @throws \Exception
  360. */
  361. public function getList($field, $where, $page, $pageSize, $order = '', $with = '')
  362. {
  363. $offset = ($page - 1) * $pageSize;
  364. $query = $this->conditionQuery($where)->select($field);
  365. $clone = clone $query;
  366. $count = $clone->count();
  367. $totalPage = ceil($count / $pageSize);
  368. $data['totalNum'] = $count;
  369. $data['totalPage'] = $totalPage;//总共页数
  370. $data['moreData'] = $totalPage > $page ? 1 : 0;//是否还有更多数据
  371. if (!empty($order)) {
  372. $query->orderBy($order);
  373. }
  374. if (!empty($with)) {
  375. $query->with($with);
  376. }
  377. $list = $query->offset($offset)->limit($pageSize)->asArray()->all();
  378. $data['list'] = $list;//数据
  379. return $data;
  380. }
  381. /**
  382. * 查询全部列表 (不分页)
  383. * @param string|array $field 查询字段
  384. * @param array $where 查询条件
  385. * @param string|array $order 排序
  386. * @param string|array $with 关联查询
  387. * @return array
  388. * @throws \Exception
  389. */
  390. public function getAllList($field, $where, $order = '', $with = '')
  391. {
  392. $query = $this->conditionQuery($where)->select($field);
  393. if (!empty($order)) {
  394. $query->orderBy($order);
  395. }
  396. if (!empty($with)) {
  397. $query->with($with);
  398. }
  399. $list = $query->asArray()->all();
  400. return $list;
  401. }
  402. /**
  403. * 查询指定条数的列表
  404. * @param string|array $field 查询字段
  405. * @param array $where 查询条件
  406. * @param int $limit 限制条数
  407. * @param string|array $order 排序
  408. * @param string|array $with 关联查询
  409. * @return array
  410. * @throws \Exception
  411. */
  412. public function getLimitList($field, $where, $limit, $order = '', $with = '')
  413. {
  414. $offset = 0;
  415. $query = $this->conditionQuery($where)->select($field);
  416. if (!empty($order)) {
  417. $query->orderBy($order);
  418. }
  419. if (!empty($with)) {
  420. $query->with($with);
  421. }
  422. $list = $query->offset($offset)->limit($limit)->asArray()->all();
  423. return $list;
  424. }
  425. /**
  426. * 更新计数器 (原子操作)
  427. * @param array $counters 更新的计数器数组,例如 ['view_count' => 1] 表示加1,['view_count' => -1] 表示减1
  428. * @param array $condition 更新条件
  429. * @param array $params 绑定参数
  430. * @return int 更新行数
  431. */
  432. public function counters($counters, $condition, $params = [])
  433. {
  434. return self::updateAllCounters($counters, $condition, $params);
  435. }
  436. /**
  437. * 获取图书的作者
  438. * @return \yii\db\ActiveQuery
  439. * @note 此方法疑似为示例代码,建议检查
  440. */
  441. public function getAuthor()
  442. {
  443. //同样第一个参数指定关联的子表模型类名
  444. return $this->hasOne(Author::className(), ['id' => 'author_id']);
  445. }
  446. /**
  447. * 根据主键获取记录并锁定 (SELECT FOR UPDATE)
  448. * @param int|string $id 主键ID
  449. * @param string|array $field 查询字段
  450. * @return array|ActiveRecord|null
  451. */
  452. public function getLockById($id, $field = '*')
  453. {
  454. return self::findBySql('select ' . $field . ' from ' . static::tableName() . ' where id = :id for update', ['id' => $id])->one();
  455. }
  456. /**
  457. * 求和
  458. * @param array $condition 查询条件
  459. * @param string $field 求和字段
  460. * @return mixed
  461. * @throws \Exception
  462. */
  463. public function sum($condition, $field)
  464. {
  465. return $this->conditionQuery($condition)->sum($field);
  466. }
  467. }