ShopGoodsSpecRelationService.php 2.2 KB

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