Category.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. <?php
  2. namespace app\common\model;
  3. use app\common\library\Service;
  4. use app\common\model\Attribute as AttributeModel;
  5. use think\Cache;
  6. use think\Db;
  7. use think\Model;
  8. /**
  9. * 分类模型
  10. */
  11. class Category extends Model
  12. {
  13. protected $name = 'shop_category';
  14. // 开启自动写入时间戳字段
  15. protected $autoWriteTimestamp = 'int';
  16. // 定义时间戳字段名
  17. protected $createTime = 'createtime';
  18. protected $updateTime = 'updatetime';
  19. // 追加属性
  20. protected $append = [
  21. ];
  22. // protected static $config = [];
  23. protected static $tagCount = 0;
  24. protected static $parentIds = null;
  25. protected static $outlinkParentIds = null;
  26. protected static $navParentIds = null;
  27. protected static function init()
  28. {
  29. // $config = get_addon_config('shop');
  30. // self::$config = $config;
  31. self::afterInsert(function ($row) {
  32. $row->save(['weigh' => $row['id']]);
  33. });
  34. }
  35. public function getImageAttr($value, $data)
  36. {
  37. $value = $value ? $value : '';
  38. return cdnurl($value, true);
  39. }
  40. public static function getIndexCategoryList()
  41. {
  42. $categoryList = self::where('status', 'normal')
  43. ->where('pid', 0)
  44. ->where("FIND_IN_SET('index',`flag`)")
  45. ->limit(9)
  46. ->order('weigh desc,id asc')
  47. ->cache(false)
  48. ->select();
  49. $categoryList = collection($categoryList)->toArray();
  50. return $categoryList;
  51. }
  52. /**
  53. * 获取栏目所有子级的ID
  54. * @param mixed $ids 栏目ID或集合ID
  55. * @param bool $withself 是否包含自身
  56. * @return array
  57. */
  58. public static function getCategoryChildrenIds($ids, $withself = true)
  59. {
  60. $cacheName = 'shop-childrens-' . $ids . '-' . $withself;
  61. $result = Cache::get($cacheName);
  62. if ($result === false) {
  63. $categoryList = Category::where('status', 'normal')
  64. ->order('weigh desc,id desc')
  65. ->cache(true, null, 'shop')
  66. ->select();
  67. $result = [];
  68. $tree = \fast\Tree::instance();
  69. $tree->init(collection($categoryList)->toArray(), 'pid');
  70. $CategoryIds = is_array($ids) ? $ids : explode(',', $ids);
  71. foreach ($CategoryIds as $index => $CategoryId) {
  72. $result = array_merge($result, $tree->getChildrenIds($CategoryId, $withself));
  73. }
  74. Cache::set($cacheName, $result);
  75. }
  76. return $result;
  77. }
  78. /**
  79. * 获取分类列表
  80. * @param $tag
  81. * @return false|\PDOStatement|string|\think\Collection
  82. */
  83. public static function getCategoryList($tag)
  84. {
  85. $type = empty($tag['type']) ? '' : $tag['type'];
  86. $typeid = !isset($tag['typeid']) ? '' : $tag['typeid'];
  87. $condition = empty($tag['condition']) ? '' : $tag['condition'];
  88. $field = empty($tag['field']) ? '*' : $tag['field'];
  89. $row = empty($tag['row']) ? 10 : (int)$tag['row'];
  90. $flag = empty($tag['flag']) ? '' : $tag['flag'];
  91. $orderby = empty($tag['orderby']) ? 'weigh' : $tag['orderby'];
  92. $orderway = empty($tag['orderway']) ? 'desc' : strtolower($tag['orderway']);
  93. $limit = empty($tag['limit']) ? $row : $tag['limit'];
  94. $orderway = in_array($orderway, ['asc', 'desc']) ? $orderway : 'desc';
  95. $paginate = !isset($tag['paginate']) ? false : $tag['paginate'];
  96. list($cacheKey, $cacheExpire) = Service::getCacheKeyExpire('categorylist', $tag);
  97. $where = ['status' => 'normal'];
  98. self::$tagCount++;
  99. if ($type === 'top') {
  100. //顶级分类
  101. $where['pid'] = 0;
  102. } elseif ($type === 'brother') {
  103. $subQuery = self::where('id', 'in', $typeid)->field('pid')->buildSql();
  104. //同级
  105. $where['pid'] = ['exp', Db::raw(' IN ' . '(' . $subQuery . ')')];
  106. } elseif ($type === 'son') {
  107. $subQuery = self::where('pid', 'in', $typeid)->field('id')->buildSql();
  108. //子级
  109. $where['id'] = ['exp', Db::raw(' IN ' . '(' . $subQuery . ')')];
  110. } elseif ($type === 'sons') {
  111. //所有子级
  112. $where['id'] = ['in', self::getCategoryChildrenIds($typeid)];
  113. } else {
  114. if ($typeid !== '') {
  115. $where['id'] = ['in', $typeid];
  116. }
  117. }
  118. //如果有设置标志,则拆分标志信息并构造condition条件
  119. if ($flag !== '') {
  120. if (stripos($flag, '&') !== false) {
  121. $arr = [];
  122. foreach (explode('&', $flag) as $k => $v) {
  123. $arr[] = "FIND_IN_SET('{$v}', flag)";
  124. }
  125. if ($arr) {
  126. $condition .= "(" . implode(' AND ', $arr) . ")";
  127. }
  128. } else {
  129. $condition .= ($condition ? ' AND ' : '');
  130. $arr = [];
  131. foreach (explode(',', str_replace('|', ',', $flag)) as $k => $v) {
  132. $arr[] = "FIND_IN_SET('{$v}', flag)";
  133. }
  134. if ($arr) {
  135. $condition .= "(" . implode(' OR ', $arr) . ")";
  136. }
  137. }
  138. }
  139. $order = $orderby == 'rand' ? Db::raw('rand()') : (preg_match("/\,|\s/", $orderby) ? $orderby : "{$orderby} {$orderway}");
  140. $order = $orderby == 'weigh' ? $order . ',id DESC' : $order;
  141. $CategoryModel = self::where($where)
  142. ->where($condition)
  143. ->field($field)
  144. ->orderRaw($order);
  145. if ($paginate) {
  146. $paginateArr = explode(',', $paginate);
  147. $listRows = is_numeric($paginate) ? $paginate : (is_numeric($paginateArr[0]) ? $paginateArr[0] : $row);
  148. $config = [];
  149. $config['var_page'] = $paginateArr[2] ?? 'cpage' . self::$tagCount;
  150. $config['path'] = $paginateArr[3] ?? '';
  151. $config['fragment'] = $paginateArr[4] ?? '';
  152. $config['query'] = request()->get();
  153. $list = $CategoryModel->paginate($listRows, ($paginateArr[1] ?? false), $config);
  154. } else {
  155. $list = $CategoryModel->limit($limit)->cache($cacheKey, $cacheExpire, 'shop')->select();
  156. }
  157. return $list;
  158. }
  159. public static function getFilterList($category, $filter, $params = [], $multiple = false)
  160. {
  161. $filterList = [];
  162. $attributeList = (new AttributeModel())->with(['AttributeValue'])->where('category_id', $category['id'])->where('is_search', 1)->select();
  163. foreach ($attributeList as $k => $v) {
  164. $v['title'] = $v['name'];
  165. $v['name'] = 'f_' . $v['id'];
  166. $content = [];
  167. $valueList = ['' => __('All')];
  168. foreach ($v['attribute_value'] as $index => $item) {
  169. $valueList[$item['id']] = $item['name'];
  170. }
  171. foreach ($valueList as $m => $n) {
  172. $filterArr = isset($filter[$v['name']]) && $filter[$v['name']] !== '' ? ($multiple ? explode(',', $filter[$v['name']]) : [$filter[$v['name']]]) : [];
  173. $active = ($m === '' && !$filterArr) || ($m !== '' && in_array($m, $filterArr)) ? true : false;
  174. if ($active) {
  175. $current = implode(',', array_diff($filterArr, [$m]));
  176. } else {
  177. $current = $multiple ? implode(',', array_merge($filterArr, [$m])) : $m;
  178. }
  179. $prepare = $m === '' ? array_diff_key($filter, [$v['name'] => $m]) : array_merge($filter, [$v['name'] => $current]);
  180. $url = '?' . str_replace(['%2C', '%3B'], [',', ';'], http_build_query(array_merge($prepare, array_intersect_key($params, array_flip(['orderby', 'orderway', 'multiple'])))));
  181. $content[] = ['value' => $m, 'title' => $n, 'active' => $active, 'url' => $url];
  182. }
  183. $filterList[] = [
  184. 'name' => $v['name'],
  185. 'title' => $v['title'],
  186. 'values' => $content,
  187. ];
  188. }
  189. foreach ($filter as $index => &$item) {
  190. $item = is_array($item) ? $item : explode(',', str_replace(';', ',', $item));
  191. }
  192. return $filterList;
  193. }
  194. public static function getCategorySubList($id)
  195. {
  196. return self::where('pid', $id)->where('status', 'normal')->order('weigh desc,id asc')->select();
  197. }
  198. public static function getCategorySubIds($id)
  199. {
  200. return self::where('pid', $id)->where('status', 'normal')->column('id');
  201. }
  202. public function Goods()
  203. {
  204. return $this->hasMany('Goods', 'category_id', 'id');
  205. }
  206. }