Goods.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. ];
  25. protected static $config = [];
  26. protected static $tagCount = 0;
  27. protected static function init()
  28. {
  29. $config = get_addon_config('shop');
  30. self::$config = $config;
  31. }
  32. public function getImageAttr($value, $data)
  33. {
  34. $value = $value ?: self::$config['default_goods_img'];
  35. return cdnurl($value, true);
  36. }
  37. public function getImagesAttr($value, $data)
  38. {
  39. $images = explode(',', $data['images'] ?? '');
  40. foreach ($images as $index => &$image) {
  41. $image && $image = cdnurl($image, true);
  42. }
  43. return array_filter($images);
  44. }
  45. public function setImagesAttr($value, $data)
  46. {
  47. return is_array($value) ? implode(',', $value) : $value;
  48. }
  49. public function getContentAttr($value, $data)
  50. {
  51. //组装卡片信息
  52. return \app\common\library\Service::formatSourceTpl($value);
  53. }
  54. public static function getIndexGoodsList()
  55. {
  56. return self::where('status', 'normal')
  57. ->where("FIND_IN_SET('recommend',`flag`)")
  58. ->order('weigh desc')
  59. ->limit(12)
  60. ->cache(false)
  61. ->select();
  62. }
  63. /**
  64. * 获取SQL查询结果
  65. */
  66. public static function getQueryList($params)
  67. {
  68. $config = get_addon_config('shop');
  69. $sql = $params['sql'] ?? '';
  70. $bind = isset($params['bind']) ? explode(',', $params['bind']) : [];
  71. list($cacheKey, $cacheExpire) = Service::getCacheKeyExpire('sql', $params);
  72. $list = Cache::tag('shop')->get($cacheKey);
  73. if (!$list) {
  74. $list = Db::query($sql, $bind);
  75. Cache::tag('shop')->set($cacheKey, $list, $cacheExpire);
  76. }
  77. return $list;
  78. }
  79. public static function refreshStar($goods_id)
  80. {
  81. $goods = self::get($goods_id);
  82. if ($goods) {
  83. $one = Comment::where('goods_id', $goods_id)->field("COUNT(*) as nums,SUM(star) as amount")->find();
  84. if ($one) {
  85. $goods->star = floor($one['amount'] / $one['nums']);
  86. $goods->save();
  87. }
  88. }
  89. }
  90. /**
  91. * 获取商品列表
  92. * @param $params
  93. * @return array|false|\PDOStatement|string|\think\Collection
  94. */
  95. public static function getGoodsList($params)
  96. {
  97. $config = get_addon_config('shop');
  98. $type = empty($params['type']) ? '' : $params['type'];
  99. $category = !isset($params['category']) ? '' : $params['category'];
  100. $condition = empty($params['condition']) ? '' : $params['condition'];
  101. $field = empty($params['field']) ? '*' : $params['field'];
  102. $flag = empty($params['flag']) ? '' : $params['flag'];
  103. $row = empty($params['row']) ? 10 : (int)$params['row'];
  104. $orderby = empty($params['orderby']) ? 'createtime' : $params['orderby'];
  105. $orderway = empty($params['orderway']) ? 'desc' : strtolower($params['orderway']);
  106. $limit = empty($params['limit']) ? $row : $params['limit'];
  107. $orderway = in_array($orderway, ['asc', 'desc']) ? $orderway : 'desc';
  108. $paginate = !isset($params['paginate']) ? false : $params['paginate'];
  109. $page = !isset($params['page']) ? 1 : (int)$params['page'];
  110. $with = !isset($params['with']) ? 'category' : $params['with'];
  111. list($cacheKey, $cacheExpire) = Service::getCacheKeyExpire('goodslist', $params);
  112. $where = ['status' => 'normal'];
  113. $where['deletetime'] = ['exp', Db::raw('IS NULL')];
  114. self::$tagCount++;
  115. $goodsModel = self::with($with)->alias('a');
  116. if ($category !== '') {
  117. $categoryIds = [];
  118. if ($type === 'son') {
  119. $subQuery = Category::where('parent_id', 'in', $category)->field('id')->buildSql();
  120. //子级
  121. $categoryIds = Db::query($subQuery);
  122. $categoryIds = array_column($categoryIds, 'id');
  123. } elseif ($type === 'sons') {
  124. //所有子级
  125. $categoryIds = Category::getCategoryChildrenIds($category);
  126. } else {
  127. $categoryIds = is_array($category) ? $category : explode(',', $category);
  128. }
  129. if (!empty($categoryIds)) {
  130. $condition .= ($condition ? ' AND ' : '') . '(';
  131. $conditionParts = [];
  132. foreach ($categoryIds as $categoryId) {
  133. $conditionParts[] = "FIND_IN_SET('{$categoryId}', category_ids)";
  134. }
  135. $condition .= implode(' OR ', $conditionParts) . ')';
  136. }
  137. }
  138. //如果有设置标志,则拆分标志信息并构造condition条件
  139. if ($flag !== '') {
  140. if (stripos($flag, '&') !== false) {
  141. $arr = [];
  142. foreach (explode('&', $flag) as $k => $v) {
  143. $arr[] = "FIND_IN_SET('{$v}', flag)";
  144. }
  145. if ($arr) {
  146. $condition .= "(" . implode(' AND ', $arr) . ")";
  147. }
  148. } else {
  149. $condition .= ($condition ? ' AND ' : '');
  150. $arr = [];
  151. foreach (explode(',', str_replace('|', ',', $flag)) as $k => $v) {
  152. $arr[] = "FIND_IN_SET('{$v}', flag)";
  153. }
  154. if ($arr) {
  155. $condition .= "(" . implode(' OR ', $arr) . ")";
  156. }
  157. }
  158. }
  159. $order = $orderby == 'rand' ? Db::raw('rand()') : (preg_match("/\,|\s/", $orderby) ? $orderby : "{$orderby} {$orderway}");
  160. $order = $orderby == 'weigh' ? $order . ',id DESC' : $order;
  161. $modelInfo = null;
  162. $prefix = config('database.prefix');
  163. $goodsModel
  164. ->where($where)
  165. ->where($condition)
  166. ->field($field, false, $prefix . "shop_goods", "a")
  167. ->orderRaw($order);
  168. if ($paginate) {
  169. $paginateArr = explode(',', $paginate);
  170. $listRows = is_numeric($paginate) ? $paginate : (is_numeric($paginateArr[0]) ? $paginateArr[0] : $row);
  171. $config = [];
  172. $config['var_page'] = $paginateArr[2] ?? (isset($params['page']) ? 'page' : 'apage' . self::$tagCount);
  173. $config['path'] = $paginateArr[3] ?? '';
  174. $config['fragment'] = $paginateArr[4] ?? '';
  175. $config['query'] = request()->get();
  176. $config['page'] = $page;
  177. $list = $goodsModel->paginate($listRows, ($paginateArr[1] ?? false), $config);
  178. } else {
  179. $list = $goodsModel->limit($limit)->cache($cacheKey, $cacheExpire, 'shop')->select();
  180. }
  181. return $list;
  182. }
  183. // public function Category()
  184. // {
  185. // // 由于现在使用category_ids字段,这里返回主分类(第一个分类)
  186. // return $this->belongsTo('Category', 'category_id', 'id');
  187. // }
  188. public function Categories()
  189. {
  190. // 新增:获取商品的所有分类
  191. $categoryIds = explode(',', $this->category_ids ?: '');
  192. return Category::where('id', 'in', array_filter($categoryIds))->select();
  193. }
  194. public function Sku()
  195. {
  196. return $this->hasMany('Sku', 'goods_id', 'id');
  197. }
  198. public function Comment()
  199. {
  200. return $this->hasMany('Comment', 'goods_id', 'id');
  201. }
  202. public function Brand()
  203. {
  204. return $this->belongsTo('Brand', 'brand_id', 'id', [], 'LEFT');
  205. }
  206. }