GoodsService.php 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. "faq_html" => $goods->faq_html,
  57. "spec_attr_html" => $goods->spec_attr_html,
  58. "is_fav" => (int)$this->goodsIsFav($goods->id),
  59. "sn" => $goods->sn,
  60. "url_3d" => $goods->url_3d,
  61. "spec_map" => $goods->specMap->map(function (GoodsSpecMap $m) {
  62. return [
  63. "id" => $m->id,
  64. "spec_id" => $m->spec_id,
  65. "value" => $m->value,
  66. "name" => $m->spec->name,
  67. "en_name" => $m->spec->en_name,
  68. ];
  69. }),
  70. "custom" => $goods->custom,
  71. ];
  72. }
  73. protected function goodsIsFav($gid): bool
  74. {
  75. $ret = false;
  76. $uid = \Auth::id();
  77. if ($uid) {
  78. if (UserFav::where("user_id", $uid)->whereGoodsId($gid)->first()) {
  79. $ret = true;
  80. }
  81. }
  82. return $ret;
  83. }
  84. }