104 lines
3.2 KiB
Lua
104 lines
3.2 KiB
Lua
local fw = require("fastweb")
|
||
local config = require("fwutils.config")
|
||
local M = {}
|
||
-- CREATE TABLE `fw_menu` (
|
||
-- `id` int NOT NULL AUTO_INCREMENT,
|
||
-- `role_id` int DEFAULT NULL,
|
||
-- `title` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
|
||
-- `path` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
|
||
-- `icon` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
|
||
-- `sort` int DEFAULT NULL,
|
||
-- `parent_id` int DEFAULT NULL,
|
||
-- PRIMARY KEY (`id`)
|
||
-- ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||
|
||
-- 更新
|
||
M.update = function(role_id,conn)
|
||
-- 查询菜单表
|
||
local select = conn:select()
|
||
select:table("fw_menu")
|
||
select:where_expression("AND delete_time IS NULL")
|
||
if role_id ~= nil then
|
||
select:where_i32("role_id", "=", role_id)
|
||
end
|
||
local result = select:query()
|
||
|
||
local bc = {}
|
||
local items_by_id = {} -- 通过id快速查找菜单项:{id = {role_id, title, item, parent_id}}
|
||
local items_with_parent = {} -- 存储有父级的菜单项
|
||
|
||
-- 第一遍:读取所有菜单项并存储
|
||
while result:next() do
|
||
local id = result:get("id")
|
||
local role_id = tostring(result:get("role_id"))
|
||
local title = result:get("title")
|
||
local path = result:get("path")
|
||
local icon = result:get("icon")
|
||
local sort = result:get("sort")
|
||
local parent_id = result:get("parent_id")
|
||
|
||
if not title or title == "" then
|
||
goto continue
|
||
end
|
||
|
||
if bc[role_id] == nil then
|
||
bc[role_id] = {}
|
||
end
|
||
|
||
local item = {
|
||
path = path,
|
||
icon = icon,
|
||
sort = sort,
|
||
}
|
||
|
||
-- 存储所有菜单项信息
|
||
items_by_id[id] = {
|
||
role_id = role_id,
|
||
title = title,
|
||
item = item,
|
||
parent_id = parent_id
|
||
}
|
||
|
||
-- 如果parent_id为空,则作为顶层菜单项
|
||
if parent_id == nil or parent_id == 0 then
|
||
bc[role_id][title] = item
|
||
else
|
||
-- 有父级,记录下来稍后处理
|
||
table.insert(items_with_parent, {
|
||
id = id,
|
||
role_id = role_id,
|
||
title = title,
|
||
item = item,
|
||
parent_id = parent_id
|
||
})
|
||
end
|
||
|
||
::continue::
|
||
end
|
||
|
||
-- 第二遍:处理有父级的菜单项,构建children结构
|
||
for _, menu_item in ipairs(items_with_parent) do
|
||
local parent_info = items_by_id[menu_item.parent_id]
|
||
if parent_info then
|
||
local parent_item = parent_info.item
|
||
|
||
-- 如果父项还没有children表,创建它
|
||
if not parent_item.children then
|
||
parent_item.children = {}
|
||
end
|
||
|
||
-- 将子项添加到父项的children中
|
||
parent_item.children[menu_item.title] = menu_item.item
|
||
end
|
||
end
|
||
|
||
local code = "return " .. require("serpent").serialize(bc, {comment = false})
|
||
utils.save_file(fw.website_dir().."/"..(config.path.luabytecode:gsub("%.", "/")).."/menu_bc.lua",code)
|
||
return true
|
||
end
|
||
M.get = function(role_id)
|
||
local menu_bc = require(config.path.luabytecode..".menu_bc")
|
||
return menu_bc[string.format("%d",role_id)]
|
||
end
|
||
|
||
return M |