123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242 |
- <?php
- namespace app\common\model;
- use app\common\library\Service;
- use app\common\model\Attribute as AttributeModel;
- use think\Cache;
- use think\Db;
- use think\Model;
- /**
- * 分类模型
- */
- class Category extends Model
- {
- protected $name = 'shop_category';
- // 开启自动写入时间戳字段
- protected $autoWriteTimestamp = 'int';
- // 定义时间戳字段名
- protected $createTime = 'createtime';
- protected $updateTime = 'updatetime';
- // 追加属性
- protected $append = [
-
- ];
- // protected static $config = [];
- protected static $tagCount = 0;
- protected static $parentIds = null;
- protected static $outlinkParentIds = null;
- protected static $navParentIds = null;
- protected static function init()
- {
- // $config = get_addon_config('shop');
- // self::$config = $config;
- self::afterInsert(function ($row) {
- $row->save(['weigh' => $row['id']]);
- });
- }
- public function getImageAttr($value, $data)
- {
- $value = $value ? $value : '';
- return cdnurl($value, true);
- }
-
- public static function getIndexCategoryList()
- {
- $categoryList = self::where('status', 'normal')
- ->where('pid', 0)
- ->where("FIND_IN_SET('index',`flag`)")
- ->limit(9)
- ->order('weigh desc,id asc')
- ->cache(false)
- ->select();
- $categoryList = collection($categoryList)->toArray();
- return $categoryList;
- }
- /**
- * 获取栏目所有子级的ID
- * @param mixed $ids 栏目ID或集合ID
- * @param bool $withself 是否包含自身
- * @return array
- */
- public static function getCategoryChildrenIds($ids, $withself = true)
- {
- $cacheName = 'shop-childrens-' . $ids . '-' . $withself;
- $result = Cache::get($cacheName);
- if ($result === false) {
- $categoryList = Category::where('status', 'normal')
- ->order('weigh desc,id desc')
- ->cache(true, null, 'shop')
- ->select();
- $result = [];
- $tree = \fast\Tree::instance();
- $tree->init(collection($categoryList)->toArray(), 'pid');
- $CategoryIds = is_array($ids) ? $ids : explode(',', $ids);
- foreach ($CategoryIds as $index => $CategoryId) {
- $result = array_merge($result, $tree->getChildrenIds($CategoryId, $withself));
- }
- Cache::set($cacheName, $result);
- }
- return $result;
- }
- /**
- * 获取分类列表
- * @param $tag
- * @return false|\PDOStatement|string|\think\Collection
- */
- public static function getCategoryList($tag)
- {
- $type = empty($tag['type']) ? '' : $tag['type'];
- $typeid = !isset($tag['typeid']) ? '' : $tag['typeid'];
- $condition = empty($tag['condition']) ? '' : $tag['condition'];
- $field = empty($tag['field']) ? '*' : $tag['field'];
- $row = empty($tag['row']) ? 10 : (int)$tag['row'];
- $flag = empty($tag['flag']) ? '' : $tag['flag'];
- $orderby = empty($tag['orderby']) ? 'weigh' : $tag['orderby'];
- $orderway = empty($tag['orderway']) ? 'desc' : strtolower($tag['orderway']);
- $limit = empty($tag['limit']) ? $row : $tag['limit'];
- $orderway = in_array($orderway, ['asc', 'desc']) ? $orderway : 'desc';
- $paginate = !isset($tag['paginate']) ? false : $tag['paginate'];
- list($cacheKey, $cacheExpire) = Service::getCacheKeyExpire('categorylist', $tag);
- $where = ['status' => 'normal'];
- self::$tagCount++;
- if ($type === 'top') {
- //顶级分类
- $where['pid'] = 0;
- } elseif ($type === 'brother') {
- $subQuery = self::where('id', 'in', $typeid)->field('pid')->buildSql();
- //同级
- $where['pid'] = ['exp', Db::raw(' IN ' . '(' . $subQuery . ')')];
- } elseif ($type === 'son') {
- $subQuery = self::where('pid', 'in', $typeid)->field('id')->buildSql();
- //子级
- $where['id'] = ['exp', Db::raw(' IN ' . '(' . $subQuery . ')')];
- } elseif ($type === 'sons') {
- //所有子级
- $where['id'] = ['in', self::getCategoryChildrenIds($typeid)];
- } else {
- if ($typeid !== '') {
- $where['id'] = ['in', $typeid];
- }
- }
- //如果有设置标志,则拆分标志信息并构造condition条件
- if ($flag !== '') {
- if (stripos($flag, '&') !== false) {
- $arr = [];
- foreach (explode('&', $flag) as $k => $v) {
- $arr[] = "FIND_IN_SET('{$v}', flag)";
- }
- if ($arr) {
- $condition .= "(" . implode(' AND ', $arr) . ")";
- }
- } else {
- $condition .= ($condition ? ' AND ' : '');
- $arr = [];
- foreach (explode(',', str_replace('|', ',', $flag)) as $k => $v) {
- $arr[] = "FIND_IN_SET('{$v}', flag)";
- }
- if ($arr) {
- $condition .= "(" . implode(' OR ', $arr) . ")";
- }
- }
- }
- $order = $orderby == 'rand' ? Db::raw('rand()') : (preg_match("/\,|\s/", $orderby) ? $orderby : "{$orderby} {$orderway}");
- $order = $orderby == 'weigh' ? $order . ',id DESC' : $order;
- $CategoryModel = self::where($where)
- ->where($condition)
- ->field($field)
- ->orderRaw($order);
- if ($paginate) {
- $paginateArr = explode(',', $paginate);
- $listRows = is_numeric($paginate) ? $paginate : (is_numeric($paginateArr[0]) ? $paginateArr[0] : $row);
- $config = [];
- $config['var_page'] = $paginateArr[2] ?? 'cpage' . self::$tagCount;
- $config['path'] = $paginateArr[3] ?? '';
- $config['fragment'] = $paginateArr[4] ?? '';
- $config['query'] = request()->get();
- $list = $CategoryModel->paginate($listRows, ($paginateArr[1] ?? false), $config);
- } else {
- $list = $CategoryModel->limit($limit)->cache($cacheKey, $cacheExpire, 'shop')->select();
- }
- return $list;
- }
- public static function getFilterList($category, $filter, $params = [], $multiple = false)
- {
- $filterList = [];
- $attributeList = (new AttributeModel())->with(['AttributeValue'])->where('category_id', $category['id'])->where('is_search', 1)->select();
- foreach ($attributeList as $k => $v) {
- $v['title'] = $v['name'];
- $v['name'] = 'f_' . $v['id'];
- $content = [];
- $valueList = ['' => __('All')];
- foreach ($v['attribute_value'] as $index => $item) {
- $valueList[$item['id']] = $item['name'];
- }
- foreach ($valueList as $m => $n) {
- $filterArr = isset($filter[$v['name']]) && $filter[$v['name']] !== '' ? ($multiple ? explode(',', $filter[$v['name']]) : [$filter[$v['name']]]) : [];
- $active = ($m === '' && !$filterArr) || ($m !== '' && in_array($m, $filterArr)) ? true : false;
- if ($active) {
- $current = implode(',', array_diff($filterArr, [$m]));
- } else {
- $current = $multiple ? implode(',', array_merge($filterArr, [$m])) : $m;
- }
- $prepare = $m === '' ? array_diff_key($filter, [$v['name'] => $m]) : array_merge($filter, [$v['name'] => $current]);
- $url = '?' . str_replace(['%2C', '%3B'], [',', ';'], http_build_query(array_merge($prepare, array_intersect_key($params, array_flip(['orderby', 'orderway', 'multiple'])))));
- $content[] = ['value' => $m, 'title' => $n, 'active' => $active, 'url' => $url];
- }
- $filterList[] = [
- 'name' => $v['name'],
- 'title' => $v['title'],
- 'values' => $content,
- ];
- }
- foreach ($filter as $index => &$item) {
- $item = is_array($item) ? $item : explode(',', str_replace(';', ',', $item));
- }
- return $filterList;
- }
- public static function getCategorySubList($id)
- {
- return self::where('pid', $id)->where('status', 'normal')->order('weigh desc,id asc')->select();
- }
- public static function getCategorySubIds($id)
- {
- return self::where('pid', $id)->where('status', 'normal')->column('id');
- }
- public function Goods()
- {
- return $this->hasMany('Goods', 'category_id', 'id');
- }
- }
|