GoodsService.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. "en_name" => $goods->en_name,
  28. "category_name" => $gmap->where("is_public", 1)->map(function (GoodsCategoryMap $map) {
  29. return optional($map->category)->name;
  30. })->implode("/"),
  31. "en_category_name" => $gmap->where("is_public", 1)->map(function (GoodsCategoryMap $map) {
  32. return optional($map->category)->en_name;
  33. })->implode("/"),
  34. "image_list" => $goods->image_list,
  35. "spec" => array_map(function ($specId) {
  36. try {
  37. /** @var Spec $spec */
  38. $spec = Spec::find($specId);
  39. return [
  40. "id" => $spec->id,
  41. "name" => $spec->name,
  42. "en_name" => $spec->en_name,
  43. "is_custom" => $spec->is_custom,
  44. "attr" => $spec->attrs->map(function (SpecAttr $a) {
  45. return [
  46. "id" => $a->id,
  47. "name" => $a->name,
  48. ];
  49. }),
  50. ];
  51. } catch (\Exception $e) {
  52. throw new ClientException("商品规格有误,请联系管理员");
  53. }
  54. }, $goods->spec),
  55. "desc_html" => $goods->desc_html,
  56. "en_desc_html" => $goods->en_desc_html,
  57. "faq_html" => $goods->faq_html,
  58. "en_faq_html" => $goods->en_faq_html,
  59. "en_spec_attr_html" => $goods->en_spec_attr_html,
  60. "is_fav" => (int)$this->goodsIsFav($goods->id),
  61. "sn" => $goods->sn,
  62. "url_3d" => $goods->url_3d,
  63. "spec_map" => $goods->specMap->map(function (GoodsSpecMap $m) {
  64. return [
  65. "id" => $m->id,
  66. "spec_id" => $m->spec_id,
  67. "value" => $m->value,
  68. "name" => $m->spec->name,
  69. "en_name" => $m->spec->en_name,
  70. ];
  71. }),
  72. "custom" => $goods->custom,
  73. ];
  74. }
  75. protected function goodsIsFav($gid): bool
  76. {
  77. $ret = false;
  78. $uid = \Auth::id();
  79. if ($uid) {
  80. if (UserFav::where("user_id", $uid)->whereGoodsId($gid)->first()) {
  81. $ret = true;
  82. }
  83. }
  84. return $ret;
  85. }
  86. }