Base.php 10 KB

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