Base.php 15 KB

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