Goods.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. <?php
  2. namespace app\common\model;
  3. use app\common\library\Service;
  4. use think\Cache;
  5. use think\Db;
  6. use think\Model;
  7. use traits\model\SoftDelete;
  8. /**
  9. * 商品模型
  10. */
  11. class Goods extends Model
  12. {
  13. use SoftDelete;
  14. // 表名
  15. protected $name = 'shop_goods';
  16. // 开启自动写入时间戳字段
  17. protected $autoWriteTimestamp = 'int';
  18. // 定义时间戳字段名
  19. protected $createTime = 'createtime';
  20. protected $updateTime = 'updatetime';
  21. protected $deleteTime = 'deletetime';
  22. // 追加属性
  23. protected $append = [
  24. 'discount_info'
  25. ];
  26. protected static $config = [];
  27. protected static $tagCount = 0;
  28. protected static function init()
  29. {
  30. $config = get_addon_config('shop');
  31. self::$config = $config;
  32. }
  33. public function getImageAttr($value, $data)
  34. {
  35. $value = $value ?: self::$config['default_goods_img'];
  36. return cdnurl($value, true);
  37. }
  38. public function getImagesAttr($value, $data)
  39. {
  40. $images = explode(',', $data['images'] ?? '');
  41. foreach ($images as $index => &$image) {
  42. $image && $image = cdnurl($image, true);
  43. }
  44. return array_filter($images);
  45. }
  46. public function setImagesAttr($value, $data)
  47. {
  48. return is_array($value) ? implode(',', $value) : $value;
  49. }
  50. public function getContentAttr($value, $data)
  51. {
  52. //组装卡片信息
  53. return \app\common\library\Service::formatSourceTpl($value);
  54. }
  55. public static function getIndexGoodsList()
  56. {
  57. return self::where('status', 'normal')
  58. ->where("FIND_IN_SET('recommend',`flag`)")
  59. ->order('weigh desc')
  60. ->limit(12)
  61. ->cache(false)
  62. ->select();
  63. }
  64. /**
  65. * 获取SQL查询结果
  66. */
  67. public static function getQueryList($params)
  68. {
  69. $config = get_addon_config('shop');
  70. $sql = $params['sql'] ?? '';
  71. $bind = isset($params['bind']) ? explode(',', $params['bind']) : [];
  72. list($cacheKey, $cacheExpire) = Service::getCacheKeyExpire('sql', $params);
  73. $list = Cache::tag('shop')->get($cacheKey);
  74. if (!$list) {
  75. $list = Db::query($sql, $bind);
  76. Cache::tag('shop')->set($cacheKey, $list, $cacheExpire);
  77. }
  78. return $list;
  79. }
  80. public static function refreshStar($goods_id)
  81. {
  82. $goods = self::get($goods_id);
  83. if ($goods) {
  84. $one = Comment::where('goods_id', $goods_id)->field("COUNT(*) as nums,SUM(star) as amount")->find();
  85. if ($one) {
  86. $goods->star = floor($one['amount'] / $one['nums']);
  87. $goods->save();
  88. }
  89. }
  90. }
  91. /**
  92. * 获取商品列表
  93. * @param $params
  94. * @return array|false|\PDOStatement|string|\think\Collection
  95. */
  96. public static function getGoodsList($params)
  97. {
  98. $config = get_addon_config('shop');
  99. $type = empty($params['type']) ? '' : $params['type'];
  100. $category = !isset($params['category']) ? '' : $params['category'];
  101. $condition = empty($params['condition']) ? '' : $params['condition'];
  102. $field = empty($params['field']) ? '*' : $params['field'];
  103. $flag = empty($params['flag']) ? '' : $params['flag'];
  104. $row = empty($params['row']) ? 10 : (int)$params['row'];
  105. $orderby = empty($params['orderby']) ? 'createtime' : $params['orderby'];
  106. $orderway = empty($params['orderway']) ? 'desc' : strtolower($params['orderway']);
  107. $limit = empty($params['limit']) ? $row : $params['limit'];
  108. $orderway = in_array($orderway, ['asc', 'desc']) ? $orderway : 'desc';
  109. $paginate = !isset($params['paginate']) ? false : $params['paginate'];
  110. $page = !isset($params['page']) ? 1 : (int)$params['page'];
  111. $with = !isset($params['with']) ? 'category' : $params['with'];
  112. list($cacheKey, $cacheExpire) = Service::getCacheKeyExpire('goodslist', $params);
  113. $where = ['status' => 'normal'];
  114. $where['deletetime'] = ['exp', Db::raw('IS NULL')];
  115. self::$tagCount++;
  116. $goodsModel = self::with($with)->alias('a');
  117. if ($category !== '') {
  118. $categoryIds = [];
  119. if ($type === 'son') {
  120. $subQuery = Category::where('parent_id', 'in', $category)->field('id')->buildSql();
  121. //子级
  122. $categoryIds = Db::query($subQuery);
  123. $categoryIds = array_column($categoryIds, 'id');
  124. } elseif ($type === 'sons') {
  125. //所有子级
  126. $categoryIds = Category::getCategoryChildrenIds($category);
  127. } else {
  128. $categoryIds = is_array($category) ? $category : explode(',', $category);
  129. }
  130. if (!empty($categoryIds)) {
  131. $condition .= ($condition ? ' AND ' : '') . '(';
  132. $conditionParts = [];
  133. foreach ($categoryIds as $categoryId) {
  134. $conditionParts[] = "FIND_IN_SET('{$categoryId}', category_ids)";
  135. }
  136. $condition .= implode(' OR ', $conditionParts) . ')';
  137. }
  138. }
  139. //如果有设置标志,则拆分标志信息并构造condition条件
  140. if ($flag !== '') {
  141. if (stripos($flag, '&') !== false) {
  142. $arr = [];
  143. foreach (explode('&', $flag) as $k => $v) {
  144. $arr[] = "FIND_IN_SET('{$v}', flag)";
  145. }
  146. if ($arr) {
  147. $condition .= "(" . implode(' AND ', $arr) . ")";
  148. }
  149. } else {
  150. $condition .= ($condition ? ' AND ' : '');
  151. $arr = [];
  152. foreach (explode(',', str_replace('|', ',', $flag)) as $k => $v) {
  153. $arr[] = "FIND_IN_SET('{$v}', flag)";
  154. }
  155. if ($arr) {
  156. $condition .= "(" . implode(' OR ', $arr) . ")";
  157. }
  158. }
  159. }
  160. $order = $orderby == 'rand' ? Db::raw('rand()') : (preg_match("/\,|\s/", $orderby) ? $orderby : "{$orderby} {$orderway}");
  161. $order = $orderby == 'weigh' ? $order . ',id DESC' : $order;
  162. $modelInfo = null;
  163. $prefix = config('database.prefix');
  164. $goodsModel
  165. ->where($where)
  166. ->where($condition)
  167. ->field($field, false, $prefix . "shop_goods", "a")
  168. ->orderRaw($order);
  169. if ($paginate) {
  170. $paginateArr = explode(',', $paginate);
  171. $listRows = is_numeric($paginate) ? $paginate : (is_numeric($paginateArr[0]) ? $paginateArr[0] : $row);
  172. $config = [];
  173. $config['var_page'] = $paginateArr[2] ?? (isset($params['page']) ? 'page' : 'apage' . self::$tagCount);
  174. $config['path'] = $paginateArr[3] ?? '';
  175. $config['fragment'] = $paginateArr[4] ?? '';
  176. $config['query'] = request()->get();
  177. $config['page'] = $page;
  178. $list = $goodsModel->paginate($listRows, ($paginateArr[1] ?? false), $config);
  179. } else {
  180. $list = $goodsModel->limit($limit)->cache($cacheKey, $cacheExpire, 'shop')->select();
  181. }
  182. return $list;
  183. }
  184. // public function Category()
  185. // {
  186. // // 由于现在使用category_ids字段,这里返回主分类(第一个分类)
  187. // return $this->belongsTo('Category', 'category_id', 'id');
  188. // }
  189. public function Categories()
  190. {
  191. // 新增:获取商品的所有分类
  192. $categoryIds = explode(',', $this->category_ids ?: '');
  193. return Category::where('id', 'in', array_filter($categoryIds))->select();
  194. }
  195. public function Sku()
  196. {
  197. return $this->hasMany('Sku', 'goods_id', 'id');
  198. }
  199. public function Comment()
  200. {
  201. return $this->hasMany('Comment', 'goods_id', 'id');
  202. }
  203. public function Brand()
  204. {
  205. return $this->belongsTo('Brand', 'brand_id', 'id', [], 'LEFT');
  206. }
  207. /**
  208. * 获取商品的折扣信息
  209. * @param $value
  210. * @param $data
  211. * @return array|null
  212. */
  213. public function getDiscountInfoAttr($value, $data)
  214. {
  215. if (!isset($data['id'])) {
  216. return null;
  217. }
  218. // 静态缓存,避免重复查询
  219. static $discountCache = [];
  220. $goodsId = $data['id'];
  221. if (!isset($discountCache[$goodsId])) {
  222. $discountCache[$goodsId] = \app\common\Service\DiscountService::getBatchGoodsDiscountInfo([$goodsId]);
  223. }
  224. return isset($discountCache[$goodsId][$goodsId]) ? $discountCache[$goodsId][$goodsId] : [];
  225. }
  226. /**
  227. * 检查商品是否有活动折扣
  228. * @param int $skuId 规格ID,单规格商品传0
  229. * @return bool
  230. */
  231. public function hasDiscount($skuId = 0)
  232. {
  233. return \app\common\Service\DiscountService::hasActiveDiscount($this->id, $skuId);
  234. }
  235. /**
  236. * 获取商品的最低折扣价格
  237. * @return float|null
  238. */
  239. public function getMinDiscountPrice()
  240. {
  241. $discountInfo = $this->discount_info;
  242. if (empty($discountInfo)) {
  243. return null;
  244. }
  245. $minPrice = null;
  246. foreach ($discountInfo as $item) {
  247. $price = floatval($item['discount_price']);
  248. if ($minPrice === null || $price < $minPrice) {
  249. $minPrice = $price;
  250. }
  251. }
  252. return $minPrice;
  253. }
  254. /**
  255. * 获取商品的最大折扣力度
  256. * @return float|null
  257. */
  258. public function getMaxDiscount()
  259. {
  260. $discountInfo = $this->discount_info;
  261. if (empty($discountInfo)) {
  262. return null;
  263. }
  264. $maxDiscount = null;
  265. foreach ($discountInfo as $item) {
  266. $discount = floatval($item['discount']);
  267. if ($maxDiscount === null || $discount < $maxDiscount) { // 折扣越小力度越大
  268. $maxDiscount = $discount;
  269. }
  270. }
  271. return $maxDiscount;
  272. }
  273. }