Base.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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] == 'between') {
  237. $param = ['between', $key, $val[1][0], $val[1][1]];
  238. } elseif ($val[0] == 'like') {
  239. $param = ['like', $key, $val[1]];
  240. } else {
  241. util::fail('非法查询方式:' . json_encode($condition));
  242. }
  243. } else {
  244. }
  245. if ($whereNum == 0) {
  246. $query->where($param);
  247. } else {
  248. $query->andWhere($param);
  249. }
  250. $whereNum++;
  251. }
  252. }
  253. return $query;
  254. }
  255. /**
  256. * 是否存在数据
  257. * @param $condition
  258. * @return bool
  259. */
  260. public function exists($condition)
  261. {
  262. return $this->conditionQuery($condition)->exists();
  263. }
  264. /**
  265. *根据条件查出多条记录
  266. */
  267. public function getAllByCondition($condition, $order = null, $field, $indexBy = null, $returnObject = false)
  268. {
  269. $query = $this->conditionQuery($condition)->select($field);
  270. if (isset($indexBy)) {
  271. $query->indexBy($indexBy);
  272. }
  273. if (isset($order)) {
  274. $query->orderBy($order);
  275. }
  276. if ($returnObject == false) {
  277. return $query->asArray()->all();
  278. } else {
  279. return $query->all();
  280. }
  281. }
  282. /**
  283. * 根据多个主键ID查询多条记录
  284. */
  285. public function getByIds($ids, $order = null, $indexBy = null, $field = '*')
  286. {
  287. $data = [];
  288. if (empty($ids)) {
  289. return $data;
  290. }
  291. $query = $this->conditionQuery(['id' => ['in', $ids]])->select($field);
  292. if (isset($indexBy)) {
  293. $query->indexBy($indexBy);
  294. }
  295. if (!empty($order)) {
  296. $query->order($order);
  297. }
  298. $data = $query->asArray()->all();
  299. return $data;
  300. }
  301. /**
  302. *根据条件查出数量
  303. */
  304. public function getCount($condition)
  305. {
  306. return $this->conditionQuery($condition)->count();
  307. }
  308. //分页查询 ssh 2019.9.21
  309. public function getList($field, $where, $page, $pageSize, $order = '', $with = '')
  310. {
  311. $offset = ($page - 1) * $pageSize;
  312. $query = $this->conditionQuery($where)->select($field);
  313. $clone = clone $query;
  314. $count = $clone->count();
  315. $totalPage = ceil($count / $pageSize);
  316. $data['totalNum'] = $count;
  317. $data['totalPage'] = $totalPage;//总共页数
  318. $data['moreData'] = $totalPage > $page ? 1 : 0;//是否还有更多数据
  319. if (!empty($order)) {
  320. $query->orderBy($order);
  321. }
  322. if (!empty($with)) {
  323. $query->with($with);
  324. }
  325. $list = $query->offset($offset)->limit($pageSize)->asArray()->all();
  326. $data['list'] = $list;//数据
  327. return $data;
  328. }
  329. //查询全部 ssh 2019.11.27
  330. public function getAllList($field, $where, $order = '', $with = '')
  331. {
  332. $query = $this->conditionQuery($where)->select($field);
  333. if (!empty($order)) {
  334. $query->orderBy($order);
  335. }
  336. if (!empty($with)) {
  337. $query->with($with);
  338. }
  339. $list = $query->asArray()->all();
  340. return $list;
  341. }
  342. //查询指定条数 ssh 2019.11.30
  343. public function getLimitList($field, $where, $limit, $order = '', $with = '')
  344. {
  345. $offset = 0;
  346. $query = $this->conditionQuery($where)->select($field);
  347. if (!empty($order)) {
  348. $query->orderBy($order);
  349. }
  350. if (!empty($with)) {
  351. $query->with($with);
  352. }
  353. $list = $query->offset($offset)->limit($limit)->asArray()->all();
  354. return $list;
  355. }
  356. /**
  357. * 计数器+1-1
  358. * $counters = ['num' => 1] 1数量+1 -1数量-1
  359. * $condition = ['id' => $id]
  360. */
  361. public function counters($counters, $condition, $params = [])
  362. {
  363. return self::updateAllCounters($counters, $condition, $params);
  364. }
  365. // 获取图书的作者
  366. public function getAuthor()
  367. {
  368. //同样第一个参数指定关联的子表模型类名
  369. return $this->hasOne(Author::className(), ['id' => 'author_id']);
  370. }
  371. //根据主键获取被销的信息 ssh 2021.5.18
  372. public function getLockById($id, $field = '*')
  373. {
  374. return self::findBySql('select ' . $field . ' from ' . static::tableName() . ' where id = :id for update', ['id' => $id])->one();
  375. }
  376. //求和
  377. public function sum($condition, $field)
  378. {
  379. return $this->conditionQuery($condition)->sum($field);
  380. }
  381. }