Category.php
2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
namespace addons\shopro\model;
use think\Model;
/**
* 配置模型
*/
class Category extends Model
{
// 表名,不含前缀
protected $name = 'shopro_category';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
protected $hidden = ['createtime', 'updatetime', 'status'];
// 追加属性
protected $append = [
];
public static function getCategoryList($id)
{
$category = self::where(['id' => $id, 'status' => 'normal'])->with('children.children.children')->find();
return $category;
}
private static function getAllChirdrenCategory($pid, $type = 'shop', $status = 'normal')
{
$where = [
'type' => $type,
'status' => $status,
'pid' => $pid
];
$categoryList = self::all($where);
if ($categoryList) {
foreach ($categoryList as $k => &$v) {
$v['chirdren'] = self::getAllChirdrenCategory($v->id);
}
return $categoryList;
}
return [];
}
/**
* 缓存递归获取子分类 id
*/
public static function getCategoryIds($id)
{
// 判断缓存
$cacheKey = 'category-' . $id . '-child-ids';
$categoryIds = cache($cacheKey);
if (!$categoryIds) {
$categoryIds = self::recursionGetCategoryIds($id);
// 存缓存
cache($cacheKey, $categoryIds, (600 + mt_rand(0, 300))); // 加入随机秒数,防止一起全部过期
}
return $categoryIds;
}
/**
* 递归获取子分类 id
*/
public static function recursionGetCategoryIds($id) {
$ids = [];
$category_ids = self::where(['pid' => $id])->column('id');
if ($category_ids) {
foreach ($category_ids as $k => $v) {
$childrenCategoryIds = self::recursionGetCategoryIds($v);
if ($childrenCategoryIds && count($childrenCategoryIds) > 0) $ids = array_merge($ids, $childrenCategoryIds);
}
}
return array_merge($ids, [intval($id)]);
}
public function getImageAttr($value, $data)
{
if (!empty($value)) return cdnurl($value, true);
}
public function children ()
{
return $this->hasMany(\addons\shopro\model\Category::class, 'pid', 'id')->where('status', 'normal')->order('weigh desc, id asc');
}
}