Currency.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace app\admin\controller;
  3. use app\BaseController;
  4. use app\admin\model\Currency as CurrencyModel;
  5. use app\admin\validate\CurrencyValidate;
  6. use Exception;
  7. use think\facade\Db;
  8. class Currency extends BaseController
  9. {
  10. /**
  11. * 删除
  12. */
  13. function delete()
  14. {
  15. Db::startTrans();
  16. try {
  17. $id = $this->request->param('id');
  18. $count = CurrencyModel::where('id', $id)->delete();
  19. if ($count < 1) throw new Exception('操作失败');
  20. Db::commit();
  21. } catch (Exception $e) {
  22. Db::rollBack();
  23. return $this->error($e->getMessage());
  24. }
  25. return $this->success('删除成功');
  26. }
  27. /**
  28. * 更新
  29. */
  30. public function update()
  31. {
  32. $errors = [];
  33. Db::startTrans();
  34. try {
  35. $params = (new CurrencyValidate)->post()->goCheck('edit');
  36. if (!empty($params['id'])) {
  37. if (CurrencyModel::where('id', "<>", $params['id'])
  38. ->where('currency', $params['currency'])->value('id')) {
  39. $errors = ['currency' => $params['currency']];
  40. throw new Exception('已存在');
  41. }
  42. $chain = CurrencyModel::where('id', $params['id'])->find();
  43. if (!$chain) {
  44. $errors = ['id' => $params['id']];
  45. throw new Exception('不存在');
  46. }
  47. unset($params['id']);
  48. $chain->update($params);
  49. } else {
  50. if (CurrencyModel::where('currency', $params['currency'])->value('id')) {
  51. $errors = [
  52. 'currency' => $params['currency'],
  53. ];
  54. throw new Exception('已存在');
  55. }
  56. unset($params['id']);
  57. CurrencyModel::create($params);
  58. }
  59. Db::commit();
  60. } catch (Exception $e) {
  61. Db::rollBack();
  62. return $this->error($e->getMessage(), $errors);
  63. }
  64. return $this->success();
  65. }
  66. /**
  67. * 列表
  68. */
  69. function list()
  70. {
  71. try {
  72. $params = $this->request->param();
  73. $page = $params['page'] ?? 1;
  74. $limit = $params['limit'] ?? 15;
  75. $query = new CurrencyModel();
  76. if (!empty($params['currency'])) {
  77. $query->where('currency', 'like', "%{$params['currency']}%");
  78. }
  79. if (!empty($params['short_currency'])) {
  80. $query->where('short_currency', 'like', "%{$params['short_currency']}%");
  81. }
  82. if (!empty($params['id'])) {
  83. $query->where('id', $params['id']);
  84. }
  85. $count = $query->count();
  86. $list = $query
  87. ->limit($limit)
  88. ->page($page)
  89. ->order('currency', 'asc')
  90. ->select()->toArray();
  91. } catch (Exception $e) {
  92. return $this->error($e->getMessage());
  93. }
  94. return $this->success(['count' => $count, 'list' => $list]);
  95. }
  96. }