GoodsService.php 2.6 KB

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