Base.php 10 KB

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