Menu.php
3.31 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
declare(strict_types=1);
namespace app\controller\admin;
use app\BaseController;
use think\facade\Db;
class Menu extends BaseController
{
/** 全部菜单树(配置用,不限角色) */
public function tree()
{
$rows = Db::name('sys_menu')
->where('status', 1)
->order('sort', 'asc')
->order('id', 'asc')
->select()
->toArray();
return json(['code' => 0, 'msg' => 'ok', 'data' => ['list' => $this->build($rows, 0)]]);
}
public function save()
{
$id = (int) $this->request->post('id', 0);
$parentId = (int) $this->request->post('parent_id', 0);
$name = trim((string) $this->request->post('name', ''));
$type = (int) $this->request->post('type', 1);
$path = trim((string) $this->request->post('path', ''));
$component = trim((string) $this->request->post('component', ''));
$perms = trim((string) $this->request->post('perms', ''));
$icon = trim((string) $this->request->post('icon', ''));
$sort = (int) $this->request->post('sort', 0);
$status = (int) $this->request->post('status', 1);
if ($name === '') {
return json(['code' => 400, 'msg' => '名称必填', 'data' => []]);
}
$now = date('Y-m-d H:i:s');
$row = [
'parent_id' => $parentId,
'name' => $name,
'type' => $type,
'path' => $path,
'component' => $component,
'perms' => $perms,
'icon' => $icon,
'sort' => $sort,
'status' => $status,
'update_time'=> $now,
];
if ($id <= 0) {
$row['create_time'] = $now;
Db::name('sys_menu')->insert($row);
} else {
Db::name('sys_menu')->where('id', $id)->update($row);
}
return json(['code' => 0, 'msg' => '已保存', 'data' => []]);
}
public function delete(int $id)
{
$child = Db::name('sys_menu')->where('parent_id', $id)->count();
if ($child > 0) {
return json(['code' => 400, 'msg' => '请先删除子菜单', 'data' => []]);
}
Db::name('sys_role_menu')->where('menu_id', $id)->delete();
Db::name('sys_menu')->where('id', $id)->delete();
return json(['code' => 0, 'msg' => '已删除', 'data' => []]);
}
/**
* @param list<array<string,mixed>> $rows
* @return list<array<string,mixed>>
*/
protected function build(array $rows, int $parentId): array
{
$out = [];
foreach ($rows as $r) {
if ((int) $r['parent_id'] !== $parentId) {
continue;
}
$out[] = [
'id' => (int) $r['id'],
'parent_id' => (int) $r['parent_id'],
'name' => $r['name'],
'type' => (int) $r['type'],
'path' => $r['path'],
'component' => $r['component'],
'perms' => $r['perms'],
'icon' => $r['icon'],
'sort' => (int) $r['sort'],
'children' => $this->build($rows, (int) $r['id']),
];
}
return $out;
}
}