119 lines
2.7 KiB
PHP
119 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace app\admin\model;
|
|
|
|
use think\Db;
|
|
use think\Model;
|
|
|
|
|
|
class Item extends Model
|
|
{
|
|
|
|
|
|
|
|
|
|
|
|
// 表名
|
|
protected $name = 'item';
|
|
|
|
// 自动写入时间戳字段
|
|
protected $autoWriteTimestamp = false;
|
|
|
|
// 定义时间戳字段名
|
|
protected $createTime = false;
|
|
protected $updateTime = false;
|
|
protected $deleteTime = false;
|
|
|
|
// 追加属性
|
|
protected $append = [
|
|
'status_text'
|
|
];
|
|
|
|
|
|
|
|
public function getStatusList()
|
|
{
|
|
return ['1' => __('Status 1'), '0' => __('Status 0')];
|
|
}
|
|
|
|
|
|
public function getStatusTextAttr($value, $data)
|
|
{
|
|
$value = $value ?: ($data['status'] ?? '');
|
|
$list = $this->getStatusList();
|
|
return $list[$value] ?? '';
|
|
}
|
|
|
|
public function getAll(){
|
|
return $this->where('status',1)
|
|
->field('id,pid,level,title,key_word,sort,status')
|
|
->select();
|
|
}
|
|
|
|
|
|
public function getList(){
|
|
$items = $this
|
|
->where('status',1)
|
|
->field(['id','title','key_word','pid'])
|
|
->order('pid','asc')
|
|
->order('sort','desc')
|
|
->select();
|
|
|
|
|
|
$this->items = $items;
|
|
$filtered = array_filter($items, function($item) {
|
|
return $item['pid'] == 0;
|
|
});
|
|
|
|
$pid_map = array_column($filtered,null,'id');
|
|
$res_items = [];
|
|
foreach ($items as $item){
|
|
if ($item['pid'] != 0 && isset($pid_map[$item['pid']])){
|
|
$res_items [] = [
|
|
...$item->toArray(),'ptitle' => $pid_map[$item['pid']]['title']
|
|
];
|
|
}
|
|
}
|
|
return $res_items;
|
|
}
|
|
|
|
public function getAllData(){
|
|
$items = $this
|
|
->where('status',1)
|
|
->field(['id','title','key_word','pid'])
|
|
->order('pid','asc')
|
|
->order('sort','desc')
|
|
->select();
|
|
$res_items = [];
|
|
foreach ($items as $item){
|
|
$res_items [] = $item->toArray();
|
|
}
|
|
return $res_items;
|
|
}
|
|
|
|
|
|
static function getAllChildIds(array $data, int $parentId): array {
|
|
// 先构建 pid 索引表,加速查找
|
|
$index = [];
|
|
foreach ($data as $item) {
|
|
$index[$item['pid']][] = $item;
|
|
}
|
|
// 递归函数,闭包形式避免污染全局
|
|
$collect = function($pid) use (&$collect, &$index) {
|
|
$ids = [];
|
|
if (isset($index[$pid])) {
|
|
foreach ($index[$pid] as $child) {
|
|
$ids[] = $child['id'];
|
|
$ids = array_merge($ids, $collect($child['id']));
|
|
}
|
|
}
|
|
return $ids;
|
|
};
|
|
|
|
return $collect($parentId);
|
|
}
|
|
|
|
|
|
|
|
}
|