GoodsService.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Modules\Mini\Services;
  3. use App\Base\BaseService;
  4. use App\Exceptions\ClientException;
  5. use App\Models\Goods\Goods;
  6. use App\Models\Goods\GoodsCategoryMap;
  7. use App\Models\Goods\GoodsSku;
  8. use App\Models\Goods\GoodsSpecMap;
  9. use App\Models\Goods\Spec;
  10. use App\Models\Goods\SpecAttr;
  11. use App\Models\User\UserFav;
  12. class GoodsService extends BaseService
  13. {
  14. public function info($params)
  15. {
  16. $id = $params['id'];
  17. $goods = Goods::where("status", Goods::STATUS_OK)->where("id", $id)->firstOrFail();
  18. $goods->view_total++;
  19. $goods->save();
  20. $gmap = $goods->map;
  21. if (!\Auth::id()) {
  22. $gmap = $goods->map->where("is_public", 1);
  23. }
  24. return [
  25. "id" => $goods->id,
  26. "name" => $goods->name,
  27. "category_name" => $gmap->where("is_public", 1)->map(function (GoodsCategoryMap $map) {
  28. return optional($map->category)->name;
  29. })->implode("/"),
  30. "image_list" => $goods->image_list,
  31. "spec" => array_map(function ($specId) {
  32. try {
  33. /** @var Spec $spec */
  34. $spec = Spec::find($specId);
  35. return [
  36. "id" => $spec->id,
  37. "name" => $spec->name,
  38. "is_custom" => $spec->is_custom,
  39. "attr" => $spec->attrs->map(function (SpecAttr $a) {
  40. return [
  41. "id" => $a->id,
  42. "name" => $a->name,
  43. ];
  44. }),
  45. ];
  46. } catch (\Exception $e) {
  47. throw new ClientException("商品规格有误,请联系管理员");
  48. }
  49. }, $goods->spec),
  50. "desc_html" => $goods->desc_html,
  51. "faq_html" => $goods->faq_html,
  52. "spec_attr_html" => $goods->spec_attr_html,
  53. "is_fav" => (int)$this->goodsIsFav($goods->id),
  54. "sn" => $goods->sn,
  55. "url_3d" => $goods->url_3d,
  56. "spec_map" => $goods->specMap->map(function (GoodsSpecMap $m) {
  57. return [
  58. "id" => $m->id,
  59. "spec_id" => $m->spec_id,
  60. "value" => $m->value,
  61. "name" => $m->spec->name,
  62. ];
  63. }),
  64. "custom" => $goods->custom,
  65. ];
  66. }
  67. protected function goodsIsFav($gid): bool
  68. {
  69. $ret = false;
  70. $uid = \Auth::id();
  71. if ($uid) {
  72. if (UserFav::where("user_id", $uid)->whereGoodsId($gid)->first()) {
  73. $ret = true;
  74. }
  75. }
  76. return $ret;
  77. }
  78. }