GoodsService.php 3.1 KB

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