GoodsService.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Modules\Admin\Services;
  3. use App\Base\BaseService;
  4. use App\Exceptions\ClientException;
  5. use App\Models\Goods\Spec;
  6. use App\Models\Goods\SpecAttr;
  7. use Illuminate\Database\Eloquent\Builder;
  8. use Illuminate\Support\Arr;
  9. use Illuminate\Support\Facades\DB;
  10. class GoodsService extends BaseService
  11. {
  12. public function specPaginate($params)
  13. {
  14. $p = Spec::query()->when($params['name'], function (Builder $query) use ($params) {
  15. return $query->where("name", 'like', "%{$params['name']}%");
  16. })->orderByDesc("id")->paginate($params['page_size']);
  17. return [
  18. "total" => $p->total(),
  19. "page_total" => $p->lastPage(),
  20. "list" => array_map(function (Spec $u) {
  21. return $u->format(Spec::FORMAT_ATTR);
  22. }, $p->items()),
  23. ];
  24. }
  25. public function specStore($params)
  26. {
  27. $id = $params['id'] ?? 0;
  28. if ($id) {
  29. $spec = Spec::find($id);
  30. } else {
  31. $spec = new Spec();
  32. }
  33. $spec->name = Arr::get($params, 'name');
  34. $spec->index_weight = Arr::get($params, 'index_weight');
  35. $spec->category_weight = Arr::get($params, 'category_weight');
  36. $spec->search_weight = Arr::get($params, 'search_weight');
  37. $spec->is_custom = (int)Arr::get($params, 'is_custom');
  38. DB::transaction(function () use ($params, $spec) {
  39. $spec->save();
  40. $attr = Arr::get($params, "attr", []);
  41. $holdIdArr = Arr::pluck($attr, "id");
  42. SpecAttr::query()->where("spec_id", $spec->id)->whereNotIn("id", $holdIdArr)->delete();
  43. foreach ($attr as $k => $v) {
  44. $id = Arr::get($v, "id");
  45. if ($id) {
  46. $m = SpecAttr::whereSpecId($spec->id)->find($id);
  47. if (is_null($m)) {
  48. logger()->error("无法保存这个属性值:" . $v['name'] ?? "");
  49. throw new ClientException("无法保存这个属性值:" . $v['name'] ?? "");
  50. }
  51. } else {
  52. $m = new SpecAttr();
  53. }
  54. $m->spec_id = $spec->id;
  55. $m->name = $v['name'] ?? "";
  56. $m->save();
  57. }
  58. });
  59. return true;
  60. }
  61. public function specInfo($data)
  62. {
  63. $id = $data['id'];
  64. $spec = Spec::findOrFail($id);
  65. return $spec->format(Spec::FORMAT_ATTR);
  66. }
  67. public function specDelete($data)
  68. {
  69. $id = $data['id'] ?? 0;
  70. // @TODO kphcdr 判断是否有商品还在使用这个规则,否则无法删除
  71. $spec = Spec::find($id);
  72. if ($spec) {
  73. SpecAttr::where("spec_id", $spec->id)->delete();
  74. $spec->delete();
  75. }
  76. return true;
  77. }
  78. }