Cps.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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\CpManage\Models\Cp;
  10. use Catch\Exceptions\FailedException;
  11. use Illuminate\Database\Eloquent\Model;
  12. use Illuminate\Support\Facades\DB;
  13. use Modules\CpManage\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. DB::commit();
  29. return $this->getKey();
  30. }else{
  31. throw new \Exception("添加失效");
  32. }
  33. }catch (\Exception $exception){
  34. DB::rollBack();
  35. throw new FailedException('添加失败!请刷新重试');
  36. }
  37. return false;
  38. }
  39. public function updateBy($id, array $data)
  40. {
  41. $updated = $this->where($this->getKeyName(), $id)->update($this->filterData($data));
  42. return $updated;
  43. }
  44. public function deleteBy($id)
  45. {
  46. $this->where($this->getKeyName(), $id)->update(['is_deleted' => 1,'deleted_at' => date("Y-m-d H:i:s")]);
  47. }
  48. protected function filterData(array $data): array
  49. {
  50. // 表单保存的数据集合
  51. $fillable = array_unique(array_merge($this->getFillable(), property_exists($this, 'form') ? $this->form : []));
  52. foreach ($data as $k => $val) {
  53. if (is_null($val) || (is_string($val) && ! $val)) {
  54. unset($data[$k]);
  55. }
  56. if (! empty($fillable) && ! in_array($k, $fillable)) {
  57. unset($data[$k]);
  58. }
  59. if (in_array($k, [$this->getUpdatedAtColumn(), $this->getCreatedAtColumn()])) {
  60. unset($data[$k]);
  61. }
  62. }
  63. return $data;
  64. }
  65. }