Cps.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. *cp管理
  4. * @file:Cps.php
  5. * @Created by gnitif
  6. * @Date: 2023/3/20
  7. * @Time: 13:57
  8. */
  9. namespace Modules\ContentManage\Models\Cp;
  10. use Catch\Exceptions\FailedException;
  11. use Illuminate\Database\Eloquent\Model;
  12. use Illuminate\Support\Facades\DB;
  13. use Modules\ContentManage\Services\CpManage\CpService;
  14. class Cps extends Model
  15. {
  16. protected $table = "cps";
  17. protected $primaryKey = "cp_id";
  18. protected $fillable = [
  19. 'cp_id', 'cp_nick', 'cp_name', 'cp_company', 'manager', 'phone', 'email', 'share_per', 'settlement_type', 'address', 'is_deleted', 'created_at', 'updated_at', 'deleted_at',
  20. ];
  21. protected array $fields = ['cp_id', 'cp_nick', 'cp_name', 'cp_company', 'manager', 'phone', 'email', 'share_per','address', 'created_at', 'updated_at'];
  22. protected array $form = ['cp_nick', 'cp_name', 'cp_company', 'manager', 'phone', 'email', 'settlement_type','share_per', 'address'];
  23. public function storeBy(array $data): mixed
  24. {
  25. DB::beginTransaction();
  26. try {
  27. if ($this->create($this->filterData($data))){
  28. #上报
  29. CpService::reportCpUser(['cp_name' => $data['cp_name']]);
  30. DB::commit();
  31. return $this->getKey();
  32. }else{
  33. throw new \Exception("添加失效");
  34. }
  35. }catch (\Exception $exception){
  36. DB::rollBack();
  37. throw new FailedException('添加失败!请刷新重试');
  38. }
  39. return false;
  40. }
  41. public function updateBy($id, array $data)
  42. {
  43. $updated = $this->where($this->getKeyName(), $id)->update($this->filterData($data));
  44. return $updated;
  45. }
  46. public function deleteBy($id)
  47. {
  48. $this->where($this->getKeyName(), $id)->update(['is_deleted' => 1,'deleted_at' => date("Y-m-d H:i:s")]);
  49. }
  50. protected function filterData(array $data): array
  51. {
  52. // 表单保存的数据集合
  53. $fillable = array_unique(array_merge($this->getFillable(), property_exists($this, 'form') ? $this->form : []));
  54. foreach ($data as $k => $val) {
  55. if (is_null($val) || (is_string($val) && ! $val)) {
  56. unset($data[$k]);
  57. }
  58. if (! empty($fillable) && ! in_array($k, $fillable)) {
  59. unset($data[$k]);
  60. }
  61. if (in_array($k, [$this->getUpdatedAtColumn(), $this->getCreatedAtColumn()])) {
  62. unset($data[$k]);
  63. }
  64. }
  65. return $data;
  66. }
  67. }