Base.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. * @return static
  9. */
  10. public function getModel()
  11. {
  12. $self = get_called_class();
  13. return new $self;
  14. }
  15. /**
  16. * 添加
  17. * @param $data
  18. * @param bool $returnObject
  19. * @return $this|array
  20. * @throws \Exception
  21. */
  22. public function add($data, $returnObject = false)
  23. {
  24. $model = $this->getModel();
  25. $attributes = $model->attributes;
  26. $fields = array_keys($attributes);
  27. foreach ($fields as $key) {
  28. if (isset($data[$key])) {
  29. $model->$key = $data[$key];
  30. }
  31. }
  32. if (!$model->validate()) {
  33. // 验证失败: $errors 是一个包含错误信息的数组
  34. \Yii::error(static::tableName() . ' -- model validate errors: ' . json_encode($model->errors));
  35. util::fail('输入数据验证失败');
  36. }
  37. // 保存数据并检查结果
  38. if (!$model->save()) {
  39. $errors = $model->errors;
  40. \Yii::error(static::tableName() . ' -- save failed: ' . json_encode($errors));
  41. throw new \Exception('数据保存失败: ' . json_encode($errors));
  42. }
  43. return $returnObject ? $model : $model->attributes;
  44. // 原有实现无异常处理
  45. // $model->save();
  46. // if ($returnObject) {
  47. // return $model;
  48. // }
  49. // return $model->attributes;
  50. }
  51. /**
  52. * 批量添加
  53. */
  54. public function batchAdd($data)
  55. {
  56. $model = $this->getModel();
  57. foreach ($data as $attributes) {
  58. $newModel = clone $model;
  59. // false 不检测字段安全 true 需要在model设置rules
  60. $newModel->setAttributes($attributes, false);
  61. $newModel->save();
  62. }
  63. }
  64. /**
  65. * 取表的字段
  66. */
  67. public function getFields()
  68. {
  69. $model = $this->getModel();
  70. $attributes = $model->attributes;
  71. return array_keys($attributes);
  72. }
  73. /**
  74. * 根据主键ID删除一条记录
  75. * @param $id
  76. * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
  77. * @throws \Throwable
  78. * @throws \yii\db\StaleObjectException
  79. */
  80. public function deleteById($id)
  81. {
  82. $model = $this->getModel();
  83. return $model::findOne($id)->delete();
  84. }
  85. /**
  86. * 根据id批量删 ssh 2019.12.7
  87. * @param $ids
  88. * @return int the number of rows deleted
  89. */
  90. public function deleteByIds($ids)
  91. {
  92. $model = $this->getModel();
  93. return $model::deleteAll(['id' => $ids]);
  94. }
  95. /**
  96. * 根据条件删除一条或多条记录
  97. * @param $condition
  98. * @return int
  99. */
  100. public function deleteByCondition($condition)
  101. {
  102. if (empty($condition)) {
  103. return 0;
  104. }
  105. $where = array();
  106. $variable = array();
  107. foreach ($condition as $key => $val) {
  108. $where[] = $key . '=:' . $key;
  109. $variable[':' . $key] = $val;
  110. }
  111. $whereString = implode(' and ', $where);
  112. $count = self::deleteAll($whereString, $variable);
  113. return $count;
  114. }
  115. /**
  116. * 根据主键ID更新一条记录
  117. */
  118. public function updateById($id, $data)
  119. {
  120. $model = $this->getModel();
  121. $attributes = $model->attributes;
  122. $fields = array_keys($attributes);
  123. foreach ($data as $key => $val) {
  124. if (in_array($key, $fields) == false) {
  125. //删除表里不存在字段
  126. unset($data[$key]);
  127. }
  128. }
  129. $re = self::updateAll($data, 'id=:id', ['id' => $id]);
  130. if ($re == 1) {
  131. return ['status' => true, 'data' => $data];
  132. }
  133. return ['status' => false, 'data' => $data];
  134. }
  135. //多个主键更新 ssh 2019.9.3
  136. public function updateByIds($ids, $data)
  137. {
  138. return self::updateAll($data, ['id' => $ids]);
  139. }
  140. /**
  141. * 根据条件更新一条或多条记录
  142. */
  143. public function updateByCondition($condition, $data)
  144. {
  145. $where = array();
  146. $variable = array();
  147. foreach ($condition as $key => $val) {
  148. $where[] = $key . '=:' . $key;
  149. $variable[':' . $key] = $val;
  150. }
  151. $whereString = implode(' and ', $where);
  152. $count = self::updateAll($data, $whereString, $variable);
  153. return $count;
  154. }
  155. /**
  156. * 根据主键ID查出一条记录
  157. * @param $id
  158. * @param bool $returnObject
  159. * @param string $field
  160. * @return array|ActiveRecord|null
  161. */
  162. public function getById($id, $returnObject = false, $field = '*')
  163. {
  164. $query = $this->conditionQuery(['id' => $id])->select($field);
  165. if ($returnObject == false) {
  166. return $query->asArray()->one();
  167. } else {
  168. return $query->one();
  169. }
  170. }
  171. /**
  172. * 根据条件查出一条记录
  173. * @param $condition
  174. * @param bool $returnObject
  175. * @param bool $order
  176. * @param string $field
  177. * @return array|ActiveRecord|null
  178. */
  179. public function getByCondition($condition, $returnObject = false, $order = false, $field = '*')
  180. {
  181. $query = $this->conditionQuery($condition)->select($field);
  182. if (isset($order)) {
  183. $query->orderBy($order);
  184. }
  185. return $returnObject == true ? $query->one() : $query->asArray()->one();
  186. }
  187. //随机取一个 ssh 2020.2.10
  188. public function getOne($returnObject = false, $order = false, $field = '*')
  189. {
  190. $query = $this->conditionQuery([])->select($field);
  191. if (isset($order)) {
  192. $query->orderBy($order);
  193. }
  194. return $returnObject == true ? $query->one() : $query->asArray()->one();
  195. }
  196. /**
  197. * 支持查询条件包括
  198. $condition = [
  199. 'name' => 'john', // 等于
  200. 'id>' => 3, // 大于
  201. 'id<' => 10, // 小于
  202. 'id!=' => -1, // 不等于
  203. 'id' => ['in', [10,11,12]], // IN
  204. 'age' => ['between', [20,30]], // BETWEEN
  205. 'name' => ['like', 'Jack'] // LIKE
  206. ];
  207. */
  208. public function conditionQuery($condition = [])
  209. {
  210. $whereNum = 0;
  211. $query = self::find();
  212. if (!empty($condition)) {
  213. foreach ($condition as $key => $val) {
  214. $param = [$key => $val];
  215. if (strstr($key, '!=')) {
  216. //不等于
  217. $pos = strpos($key, '!=');
  218. $currentKey = substr($key, 0, $pos);
  219. $param = ['!=', $currentKey, $val];
  220. } elseif (strstr($key, '>')) {
  221. //暂不支持大于等于,等于请使用between
  222. $pos = strpos($key, '>');
  223. $currentKey = substr($key, 0, $pos);
  224. $param = ['>', $currentKey, $val];
  225. } elseif (strstr($key, '<')) {
  226. //暂不支持小于等于,等于请使用between
  227. $pos = strpos($key, '<');
  228. $currentKey = substr($key, 0, $pos);
  229. $param = ['<', $currentKey, $val];
  230. } elseif (is_array($val)) {
  231. if (count($val) != 2) {
  232. util::fail('参数不至2个,非法查询方式:' . json_encode($condition));
  233. }
  234. if ($val[0] == 'in') {
  235. $param = ['in', $key, $val[1]];
  236. } elseif ($val[0] == 'not in') {
  237. $param = ['not in', $key, $val[1]];
  238. } elseif ($val[0] == 'between') {
  239. $param = ['between', $key, $val[1][0], $val[1][1]];
  240. } elseif ($val[0] == 'like') {
  241. $param = ['like', $key, $val[1]];
  242. } else {
  243. util::fail('非法查询方式:' . json_encode($condition));
  244. }
  245. } else {
  246. }
  247. if ($whereNum == 0) {
  248. $query->where($param);
  249. } else {
  250. $query->andWhere($param);
  251. }
  252. $whereNum++;
  253. }
  254. }
  255. return $query;
  256. }
  257. /**
  258. * 是否存在数据
  259. * @param $condition
  260. * @return bool
  261. */
  262. public function exists($condition)
  263. {
  264. return $this->conditionQuery($condition)->exists();
  265. }
  266. /**
  267. *根据条件查出多条记录
  268. */
  269. public function getAllByCondition($condition, $order = null, $field, $indexBy = null, $returnObject = false)
  270. {
  271. $query = $this->conditionQuery($condition)->select($field);
  272. if (isset($indexBy)) {
  273. $query->indexBy($indexBy);
  274. }
  275. if (isset($order)) {
  276. $query->orderBy($order);
  277. }
  278. if ($returnObject == false) {
  279. return $query->asArray()->all();
  280. } else {
  281. return $query->all();
  282. }
  283. }
  284. /**
  285. * 根据多个主键ID查询多条记录
  286. */
  287. public function getByIds($ids, $order = null, $indexBy = null, $field = '*')
  288. {
  289. $data = [];
  290. if (empty($ids)) {
  291. return $data;
  292. }
  293. $query = $this->conditionQuery(['id' => ['in', $ids]])->select($field);
  294. if (isset($indexBy)) {
  295. $query->indexBy($indexBy);
  296. }
  297. if (!empty($order)) {
  298. $query->order($order);
  299. }
  300. $data = $query->asArray()->all();
  301. return $data;
  302. }
  303. /**
  304. *根据条件查出数量
  305. */
  306. public function getCount($condition)
  307. {
  308. return $this->conditionQuery($condition)->count();
  309. }
  310. //分页查询 ssh 2019.9.21
  311. public function getList($field, $where, $page, $pageSize, $order = '', $with = '')
  312. {
  313. $offset = ($page - 1) * $pageSize;
  314. $query = $this->conditionQuery($where)->select($field);
  315. $clone = clone $query;
  316. $count = $clone->count();
  317. $totalPage = ceil($count / $pageSize);
  318. $data['totalNum'] = $count;
  319. $data['totalPage'] = $totalPage;//总共页数
  320. $data['moreData'] = $totalPage > $page ? 1 : 0;//是否还有更多数据
  321. if (!empty($order)) {
  322. $query->orderBy($order);
  323. }
  324. if (!empty($with)) {
  325. $query->with($with);
  326. }
  327. $list = $query->offset($offset)->limit($pageSize)->asArray()->all();
  328. $data['list'] = $list;//数据
  329. return $data;
  330. }
  331. //查询全部 ssh 2019.11.27
  332. public function getAllList($field, $where, $order = '', $with = '')
  333. {
  334. $query = $this->conditionQuery($where)->select($field);
  335. if (!empty($order)) {
  336. $query->orderBy($order);
  337. }
  338. if (!empty($with)) {
  339. $query->with($with);
  340. }
  341. $list = $query->asArray()->all();
  342. return $list;
  343. }
  344. //查询指定条数 ssh 2019.11.30
  345. public function getLimitList($field, $where, $limit, $order = '', $with = '')
  346. {
  347. $offset = 0;
  348. $query = $this->conditionQuery($where)->select($field);
  349. if (!empty($order)) {
  350. $query->orderBy($order);
  351. }
  352. if (!empty($with)) {
  353. $query->with($with);
  354. }
  355. $list = $query->offset($offset)->limit($limit)->asArray()->all();
  356. return $list;
  357. }
  358. /**
  359. * 计数器+1-1
  360. * $counters = ['num' => 1] 1数量+1 -1数量-1
  361. * $condition = ['id' => $id]
  362. */
  363. public function counters($counters, $condition, $params = [])
  364. {
  365. return self::updateAllCounters($counters, $condition, $params);
  366. }
  367. // 获取图书的作者
  368. public function getAuthor()
  369. {
  370. //同样第一个参数指定关联的子表模型类名
  371. return $this->hasOne(Author::className(), ['id' => 'author_id']);
  372. }
  373. //根据主键获取被销的信息 ssh 2021.5.18
  374. public function getLockById($id, $field = '*')
  375. {
  376. return self::findBySql('select ' . $field . ' from ' . static::tableName() . ' where id = :id for update', ['id' => $id])->one();
  377. }
  378. //求和
  379. public function sum($condition, $field)
  380. {
  381. return $this->conditionQuery($condition)->sum($field);
  382. }
  383. }