Base.php 11 KB

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