Base.php 12 KB

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