| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- <?php
- namespace app\common\service;
- use app\common\model\ShopGoodsSpecRelationModel;
- use utils\RedisCache;
- /**
- * 商品规格关系服务 by wes
- * Class ShopGoodsSpecRelationService
- * @package app\common\service
- */
- class ShopGoodsSpecRelationService
- {
- protected static $instance = null;
- protected $model = null;
- public function __construct()
- {
- $this->model = new ShopGoodsSpecRelationModel();
- }
- /**
- * 静态化入口
- * @return static|null
- */
- public static function make()
- {
- if(!self::$instance){
- self::$instance = new static();
- }
- return self::$instance;
- }
- /**
- * 获取商品对应数据
- * @param $goodsId 商品ID
- * @param string $field 字段
- * @param $cache 是否缓存数据,默认是
- * @return array|mixed
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- */
- public function getDataByGoods($goodsId, $field='', $cache=true)
- {
- $cacheKey = "caches:goodsSpec:relation_{$goodsId}".($field? '_'.md5($field):'');
- $list = RedisCache::get($cacheKey);
- if($list && $cache){
- return $list;
- }
- $where = ['goods_id'=> $goodsId];
- $field = $field? $field : 'spec_name,spec_value';
- $data = $this->model->where($where)->field($field)
- ->withAttr('spec_value', function ($value) {
- return json_decode($value, true);
- })->select();
- $data = $data? $data->toArray():[];
- if($data){
- RedisCache::set($cacheKey, $data, rand(5,10));
- }
- return $data;
- }
- }
|