Base.php 11 KB

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