Base.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. return 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, $field = '*')
  135. {
  136. $query = $this->conditionQuery(['id' => $id])->select($field);
  137. if ($returnObject == false) {
  138. return $query->asArray()->one();
  139. } else {
  140. return $query->one();
  141. }
  142. }
  143. /**
  144. *根据条件查出一条记录
  145. */
  146. public function getByCondition($condition, $returnObject = false, $order = false, $field = '*')
  147. {
  148. $query = $this->conditionQuery($condition)->select($field);
  149. if (isset($order)) {
  150. $query->orderBy($order);
  151. }
  152. return $returnObject == true ? $query->one() : $query->asArray()->one();
  153. }
  154. //随机取一个 ssh 2020.2.10
  155. public function getOne($returnObject = false, $order = false, $field = '*')
  156. {
  157. $query = $this->conditionQuery([])->select($field);
  158. if (isset($order)) {
  159. $query->orderBy($order);
  160. }
  161. return $returnObject == true ? $query->one() : $query->asArray()->one();
  162. }
  163. /**
  164. * 支持查询条件包括
  165. * ['name'=>'john','id>'=>3,'id<'=>10,'id'=>['in',[10,11,12]],'age'=>['between',[20,30]],'name'=>['like','Jack']];
  166. */
  167. public function conditionQuery($condition = [])
  168. {
  169. $whereNum = 0;
  170. $query = self::find();
  171. if (!empty($condition)) {
  172. foreach ($condition as $key => $val) {
  173. $param = [$key => $val];
  174. if (strstr($key, '>')) {
  175. //暂不支持大于等于,等于请使用between
  176. $pos = strpos($key, '>');
  177. $currentKey = substr($key, 0, $pos);
  178. $param = ['>', $currentKey, $val];
  179. } elseif (strstr($key, '<')) {
  180. //暂不支持小于等于,等于请使用between
  181. $pos = strpos($key, '<');
  182. $currentKey = substr($key, 0, $pos);
  183. $param = ['<', $currentKey, $val];
  184. } elseif (is_array($val)) {
  185. if (count($val) != 2) {
  186. util::fail('参数不至2个,非法查询方式:' . json_encode($condition));
  187. }
  188. if ($val[0] == 'in') {
  189. $param = ['in', $key, $val[1]];
  190. } elseif ($val[0] == 'between') {
  191. $param = ['between', $key, $val[1][0], $val[1][1]];
  192. } elseif ($val[0] == 'like') {
  193. $param = ['like', $key, $val[1]];
  194. } else {
  195. util::fail('非法查询方式:' . json_encode($condition));
  196. }
  197. } else {
  198. }
  199. if ($whereNum == 0) {
  200. $query->where($param);
  201. } else {
  202. $query->andWhere($param);
  203. }
  204. $whereNum++;
  205. }
  206. }
  207. return $query;
  208. }
  209. //是否存在数据 ssh 2019.
  210. public function exists($condition)
  211. {
  212. return $this->conditionQuery($condition)->exists();
  213. }
  214. /**
  215. *根据条件查出多条记录
  216. */
  217. public function getAllByCondition($condition, $order = null, $field, $indexBy = null, $returnObject = false)
  218. {
  219. $query = $this->conditionQuery($condition)->select($field);
  220. if (isset($indexBy)) {
  221. $query->indexBy($indexBy);
  222. }
  223. if (isset($order)) {
  224. $query->orderBy($order);
  225. }
  226. if ($returnObject == false) {
  227. return $query->asArray()->all();
  228. } else {
  229. return $query->all();
  230. }
  231. }
  232. /**
  233. * 根据多个主键ID查询多条记录
  234. */
  235. public function getByIds($ids, $order = null, $indexBy = null, $field = '*')
  236. {
  237. $data = [];
  238. if (empty($ids)) {
  239. return $data;
  240. }
  241. $query = $this->conditionQuery(['id' => ['in', $ids]])->select($field);
  242. if (isset($indexBy)) {
  243. $query->indexBy($indexBy);
  244. }
  245. if (!empty($order)) {
  246. $query->order($order);
  247. }
  248. $data = $query->asArray()->all();
  249. return $data;
  250. }
  251. /**
  252. *根据条件查出数量
  253. */
  254. public function getCount($condition)
  255. {
  256. return $this->conditionQuery($condition)->count();
  257. }
  258. //分页查询 ssh 2019.9.21
  259. public function getList($field, $where, $page, $pageSize, $order = '', $with = '')
  260. {
  261. $offset = ($page - 1) * $pageSize;
  262. $query = $this->conditionQuery($where)->select($field);
  263. $clone = clone $query;
  264. $count = $clone->count();
  265. $totalPage = ceil($count / $pageSize);
  266. $data['totalNum'] = $count;
  267. $data['totalPage'] = $totalPage;//总共页数
  268. $data['moreData'] = $totalPage > $page ? 1 : 0;//是否还有更多数据
  269. if (!empty($order)) {
  270. $query->orderBy($order);
  271. }
  272. if (!empty($with)) {
  273. $query->with($with);
  274. }
  275. $list = $query->offset($offset)->limit($pageSize)->asArray()->all();
  276. $data['list'] = $list;//数据
  277. return $data;
  278. }
  279. //查询全部 ssh 2019.11.27
  280. public function getAllList($field, $where, $order = '', $with = '')
  281. {
  282. $query = $this->conditionQuery($where)->select($field);
  283. if (!empty($order)) {
  284. $query->orderBy($order);
  285. }
  286. if (!empty($with)) {
  287. $query->with($with);
  288. }
  289. $list = $query->asArray()->all();
  290. return $list;
  291. }
  292. //查询指定条数 ssh 2019.11.30
  293. public function getLimitList($field, $where, $limit, $order = '', $with = '')
  294. {
  295. $offset = 0;
  296. $query = $this->conditionQuery($where)->select($field);
  297. if (!empty($order)) {
  298. $query->orderBy($order);
  299. }
  300. if (!empty($with)) {
  301. $query->with($with);
  302. }
  303. $list = $query->offset($offset)->limit($limit)->asArray()->all();
  304. return $list;
  305. }
  306. /**
  307. * 计数器+1-1
  308. * $counters = ['num' => 1] 1数量+1 -1数量-1
  309. * $condition = ['id' => $id]
  310. */
  311. public function counters($counters, $condition, $params = [])
  312. {
  313. return self::updateAllCounters($counters, $condition, $params);
  314. }
  315. // 获取图书的作者
  316. public function getAuthor()
  317. {
  318. //同样第一个参数指定关联的子表模型类名
  319. return $this->hasOne(Author::className(), ['id' => 'author_id']);
  320. }
  321. //根据主键获取被销的信息 ssh 2021.5.18
  322. public function getLockById($id, $field = '*')
  323. {
  324. return self::findBySql('select ' . $field . ' from ' . static::tableName() . ' where id = :id for update', ['id' => $id])->one();
  325. }
  326. //求和
  327. public function sum($condition, $field)
  328. {
  329. return $this->conditionQuery($condition)->sum($field);
  330. }
  331. }