Goods.php 8.1 KB

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