通过Lua实现动态传参

  其他常见问题
内容纲要

概要描述


再midgard的sql模式使用中,经常会有客户将一个列作为筛选条件希望达到我对这个列输入值的时候实现筛选而不输入值得时候就做全表查询得需求,而我们的入参无论选择是否必填实际上都是需要填写得,这种需求只用通过java或者lua来实现,这篇文章将介绍通过lua入参映射得方式实现这个需求。

详细说明


原始入参

这里将b列设定为入参参数$id来作为筛选条件
file
file

入参映射

再这里配置上对应的lua脚本
file

local condition = ""
if ${id} and ${id} ~= "" then
condition= " and b LIKE '%" .. ${id} .. "%'"
end
return condition

验证sql

测试api获得结果:
file
file
dba上面观察到的sql:
file

当不输入id的时候:
file
file
file

其他信息


多种写法

这里只是提供一种lua脚本的参考的写法,也可以直接把 1=1写到condition中变成

local condition = "1=1"
if ${id} ~= nil then
condition = condition .. " AND id like '%" .. ${id} .. "%'"
end
return condition

输出日志

如果不清楚自己脚本逻辑哪里有问题也可以输出日志,会输出再apisix的error.log日志中:

if ${project_number} ~= nil then
condition = condition .. " AND project_number like '%" .. ${project_number} .. "%'"
end
if ${usercode} and ${usercode} ~= '' then
condition = condition .. " and project_manager_labor_number = '" .. ${usercode} .. "' or control_manager_number = '" .. ${usercode} .. "' or purchase_manager_number = '" .. ${usercode} .. "'"
end
local core = require("apisix.core")
core.log.error(" condition is " .. condition .. ", project_number is " .. project_number ..  " , usercode is " .. usercode)
return condition

这篇文章对您有帮助吗?

平均评分 0 / 5. 次数: 0

尚无评价,您可以第一个评哦!

非常抱歉,这篇文章对您没有帮助.

烦请您告诉我们您的建议与意见,以便我们改进,谢谢您。