Goods.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. use app\common\Service\ShopConfigService;
  9. /**
  10. * 商品模型
  11. */
  12. class Goods extends Model
  13. {
  14. use SoftDelete;
  15. // 表名
  16. protected $name = 'shop_goods';
  17. // 开启自动写入时间戳字段
  18. protected $autoWriteTimestamp = 'int';
  19. // 定义时间戳字段名
  20. protected $createTime = 'createtime';
  21. protected $updateTime = 'updatetime';
  22. protected $deleteTime = 'deletetime';
  23. // 追加属性
  24. protected $append = [
  25. ];
  26. protected static $config = [];
  27. protected static $tagCount = 0;
  28. protected static function init()
  29. {
  30. $config = ShopConfigService::getConfigs('shop.goods',false);
  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 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. $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. $type = empty($params['type']) ? '' : $params['type'];
  98. $category = !isset($params['category']) ? '' : $params['category'];
  99. $condition = empty($params['condition']) ? '' : $params['condition'];
  100. $field = empty($params['field']) ? '*' : $params['field'];
  101. $flag = empty($params['flag']) ? '' : $params['flag'];
  102. $row = empty($params['row']) ? 10 : (int)$params['row'];
  103. $orderby = empty($params['orderby']) ? 'createtime' : $params['orderby'];
  104. $orderway = empty($params['orderway']) ? 'desc' : strtolower($params['orderway']);
  105. $limit = empty($params['limit']) ? $row : $params['limit'];
  106. $orderway = in_array($orderway, ['asc', 'desc']) ? $orderway : 'desc';
  107. $paginate = !isset($params['paginate']) ? false : $params['paginate'];
  108. $page = !isset($params['page']) ? 1 : (int)$params['page'];
  109. $with = !isset($params['with']) ? 'category' : $params['with'];
  110. list($cacheKey, $cacheExpire) = Service::getCacheKeyExpire('goodslist', $params);
  111. $where = ['status' => 'normal'];
  112. $where['deletetime'] = ['exp', Db::raw('IS NULL')];
  113. self::$tagCount++;
  114. $goodsModel = self::with($with)->alias('a');
  115. if ($category !== '') {
  116. $categoryIds = [];
  117. if ($type === 'son') {
  118. $subQuery = Category::where('parent_id', 'in', $category)->field('id')->buildSql();
  119. //子级
  120. $categoryIds = Db::query($subQuery);
  121. $categoryIds = array_column($categoryIds, 'id');
  122. } elseif ($type === 'sons') {
  123. //所有子级
  124. $categoryIds = Category::getCategoryChildrenIds($category);
  125. } else {
  126. $categoryIds = is_array($category) ? $category : explode(',', $category);
  127. }
  128. if (!empty($categoryIds)) {
  129. $condition .= ($condition ? ' AND ' : '') . '(';
  130. $conditionParts = [];
  131. foreach ($categoryIds as $categoryId) {
  132. $conditionParts[] = "FIND_IN_SET('{$categoryId}', category_ids)";
  133. }
  134. $condition .= implode(' OR ', $conditionParts) . ')';
  135. }
  136. }
  137. //如果有设置标志,则拆分标志信息并构造condition条件
  138. if ($flag !== '') {
  139. if (stripos($flag, '&') !== false) {
  140. $arr = [];
  141. foreach (explode('&', $flag) as $k => $v) {
  142. $arr[] = "FIND_IN_SET('{$v}', flag)";
  143. }
  144. if ($arr) {
  145. $condition .= "(" . implode(' AND ', $arr) . ")";
  146. }
  147. } else {
  148. $condition .= ($condition ? ' AND ' : '');
  149. $arr = [];
  150. foreach (explode(',', str_replace('|', ',', $flag)) as $k => $v) {
  151. $arr[] = "FIND_IN_SET('{$v}', flag)";
  152. }
  153. if ($arr) {
  154. $condition .= "(" . implode(' OR ', $arr) . ")";
  155. }
  156. }
  157. }
  158. $order = $orderby == 'rand' ? Db::raw('rand()') : (preg_match("/\,|\s/", $orderby) ? $orderby : "{$orderby} {$orderway}");
  159. $order = $orderby == 'weigh' ? $order . ',id DESC' : $order;
  160. $modelInfo = null;
  161. $prefix = config('database.prefix');
  162. $goodsModel
  163. ->where($where)
  164. ->where($condition)
  165. ->field($field, false, $prefix . "shop_goods", "a")
  166. ->orderRaw($order);
  167. if ($paginate) {
  168. $paginateArr = explode(',', $paginate);
  169. $listRows = is_numeric($paginate) ? $paginate : (is_numeric($paginateArr[0]) ? $paginateArr[0] : $row);
  170. $config = [];
  171. $config['var_page'] = $paginateArr[2] ?? (isset($params['page']) ? 'page' : 'apage' . self::$tagCount);
  172. $config['path'] = $paginateArr[3] ?? '';
  173. $config['fragment'] = $paginateArr[4] ?? '';
  174. $config['query'] = request()->get();
  175. $config['page'] = $page;
  176. $list = $goodsModel->paginate($listRows, ($paginateArr[1] ?? false), $config);
  177. } else {
  178. $list = $goodsModel->limit($limit)->cache($cacheKey, $cacheExpire, 'shop')->select();
  179. }
  180. return $list;
  181. }
  182. // public function Category()
  183. // {
  184. // // 由于现在使用category_ids字段,这里返回主分类(第一个分类)
  185. // return $this->belongsTo('Category', 'category_id', 'id');
  186. // }
  187. public function Categories()
  188. {
  189. // 新增:获取商品的所有分类
  190. $categoryIds = explode(',', $this->category_ids ?: '');
  191. return Category::where('id', 'in', array_filter($categoryIds))->select();
  192. }
  193. public function Sku()
  194. {
  195. return $this->hasMany('Sku', 'goods_id', 'id');
  196. }
  197. public function Comment()
  198. {
  199. return $this->hasMany('Comment', 'goods_id', 'id');
  200. }
  201. public function Brand()
  202. {
  203. return $this->belongsTo('Brand', 'brand_id', 'id', [], 'LEFT');
  204. }
  205. }