Cps.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. class Cps extends Model
  14. {
  15. protected $table = "cps";
  16. protected $primaryKey = "cp_id";
  17. protected $fillable = [
  18. 'cp_id', 'cp_nick', 'cp_name', 'cp_company', 'manager', 'phone', 'email', 'share_per', 'settlement_type', 'address', 'is_deleted', 'created_at', 'updated_at', 'deleted_at',
  19. ];
  20. protected array $fields = ['cp_id', 'cp_nick', 'cp_name', 'cp_company', 'manager', 'phone', 'email', 'share_per','address', 'created_at', 'updated_at'];
  21. protected array $form = ['cp_nick', 'cp_name', 'cp_company', 'manager', 'phone', 'email', 'settlement_type','share_per', 'address'];
  22. public function storeBy(array $data): mixed
  23. {
  24. DB::beginTransaction();
  25. try {
  26. if ($this->create($this->filterData($data))){
  27. DB::commit();
  28. return $this->getKey();
  29. }else{
  30. throw new \Exception("添加失效");
  31. }
  32. }catch (\Exception $exception){
  33. DB::rollBack();
  34. throw new FailedException('添加失败!请刷新重试');
  35. }
  36. return false;
  37. }
  38. public function updateBy($id, array $data)
  39. {
  40. $updated = $this->where($this->getKeyName(), $id)->update($this->filterData($data));
  41. return $updated;
  42. }
  43. public function deleteBy($id)
  44. {
  45. $this->where($this->getKeyName(), $id)->update(['is_deleted' => 1,'deleted_at' => date("Y-m-d H:i:s")]);
  46. }
  47. protected function filterData(array $data): array
  48. {
  49. // 表单保存的数据集合
  50. $fillable = array_unique(array_merge($this->getFillable(), property_exists($this, 'form') ? $this->form : []));
  51. foreach ($data as $k => $val) {
  52. if (is_null($val) || (is_string($val) && ! $val)) {
  53. unset($data[$k]);
  54. }
  55. if (! empty($fillable) && ! in_array($k, $fillable)) {
  56. unset($data[$k]);
  57. }
  58. if (in_array($k, [$this->getUpdatedAtColumn(), $this->getCreatedAtColumn()])) {
  59. unset($data[$k]);
  60. }
  61. }
  62. return $data;
  63. }
  64. }