CurdControllerTrait.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2017/11/15
  6. */
  7. namespace crmeb\traits;
  8. use crmeb\utils\Json;
  9. use think\Request;
  10. trait CurdControllerTrait
  11. {
  12. /**
  13. * 错误信息
  14. * @var string
  15. */
  16. protected $errorInfo;
  17. /**保存数据库
  18. * @param $id
  19. * @param $field
  20. */
  21. public function change_field($id, $field)
  22. {
  23. if (!isset($this->bindModel)) return exception('方法不存在!');
  24. if (!class_exists($this->bindModel)) return Json::fail('操作Model不存在!');
  25. $model = new $this->bindModel;
  26. $pk = $model->getPk();
  27. if (strtolower($pk) == strtolower($field)) return Json::fail('主键不允许修改!');
  28. $data = $model->where($pk, $id)->find();
  29. if (!$data) JsonService::fail('记录不存在!');
  30. $value = app('request')->post($field);
  31. if ($value === null) return Json::fail('请提交需要编辑的数据!');
  32. $data->$field = $value;
  33. return false !== $data->save() ? Json::successful('编辑成功!') : Json::fail('编辑失败!');
  34. }
  35. /**
  36. * 修改数据信息
  37. * @param $id
  38. * @param array|null $updateData
  39. * @return bool
  40. */
  41. public function model_save($id, array $updateData = null)
  42. {
  43. if (!class_exists($this->bindModel)) return $this->setErrorInfo('操作Model不存在!');
  44. $model = new $this->bindModel;
  45. $pk = $model->getPk();
  46. if (!($modelData = $model->where($pk, $id)->find())) return $this->setErrorInfo('修改的信息不存在');
  47. $data = $updateData ?: app('request')->post();
  48. if ($data === null || !is_array($data)) return $this->setErrorInfo('请提交需要修改的数据');
  49. $dataKey = array_keys($data);
  50. if (in_array($pk, $dataKey)) return $this->setErrorInfo('主键不允许修改');
  51. foreach ($data as $key => $value) {
  52. $modelData->{$key} = $value;
  53. }
  54. return $modelData->save() ? true : $this->setErrorInfo('保存失败');
  55. }
  56. /**
  57. * 设置错误信息
  58. * @param $errorInfo
  59. * @return bool
  60. */
  61. public function setErrorInfo($errorInfo)
  62. {
  63. $this->errorInfo = $errorInfo;
  64. return false;
  65. }
  66. /**
  67. * 获取错误信息
  68. * @param string|null $msgError
  69. * @return string
  70. */
  71. public function getErrorInfo(string $msgError = null)
  72. {
  73. $errorInfo = $this->errorInfo ?: $msgError;
  74. $this->errorInfo = null;
  75. return $errorInfo;
  76. }
  77. }