ShopGoodsSpecRelationService.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace app\common\service;
  3. use app\common\model\ShopGoodsSpecRelationModel;
  4. use utils\RedisCache;
  5. /**
  6. * 商品规格关系服务 by wes
  7. * Class ShopGoodsSpecRelationService
  8. * @package app\common\service
  9. */
  10. class ShopGoodsSpecRelationService
  11. {
  12. protected static $instance = null;
  13. protected $model = null;
  14. public function __construct()
  15. {
  16. $this->model = new ShopGoodsSpecRelationModel();
  17. }
  18. /**
  19. * 静态化入口
  20. * @return static|null
  21. */
  22. public static function make()
  23. {
  24. if(!self::$instance){
  25. self::$instance = new static();
  26. }
  27. return self::$instance;
  28. }
  29. /**
  30. * 获取商品对应数据
  31. * @param $goodsId 商品ID
  32. * @param string $field 字段
  33. * @param $cache 是否缓存数据,默认是
  34. * @return array|mixed
  35. * @throws \think\db\exception\DataNotFoundException
  36. * @throws \think\db\exception\DbException
  37. * @throws \think\db\exception\ModelNotFoundException
  38. */
  39. public function getDataByGoods($goodsId, $field='', $cache=true)
  40. {
  41. $cacheKey = "caches:goodsSpec:relation_{$goodsId}".($field? '_'.md5($field):'');
  42. $list = RedisCache::get($cacheKey);
  43. if($list && $cache){
  44. return $list;
  45. }
  46. $where = ['goods_id'=> $goodsId];
  47. $field = $field? $field : 'spec_name,spec_value';
  48. $data = $this->model->where($where)->field($field)
  49. ->withAttr('spec_value', function ($value) {
  50. return json_decode($value, true);
  51. })->select();
  52. $data = $data? $data->toArray():[];
  53. if($data){
  54. RedisCache::set($cacheKey, $data, rand(5,10));
  55. }
  56. return $data;
  57. }
  58. }