基于传递给控制器的参数动态创建查询 [英] Dynamically creating a query based on params being passed to a controller
问题描述
在我的任务管理应用程序中,用户应该能够根据 assignedTo
, priority
, status
和/或 dueDate
我不确定如何创建一个动态查询,它将根据可用参数构建查询。
例如:
如果我有一个URL,例如: task / index?assignedTo = 1& status = 2
I可以仅基于这两个参数构建查询。我习惯的方法是
pre $ Task.findAllByAssignedToAndStatus(
User.get(params.assignedTo),
TaskStatus.get(params.status)
)
我显然不想通过为每个可能的URL参数组合写出每个 findAllBy
查询来实现DRY方法。
有没有一种好方法在grails中这样做?
我设法使用 createCriteria
,如下所示:
如果用户为该特定过滤器选择全部,则对任何参数使用值0,因此它将从where子句,即没有 eq()
语句。
代码片段:
else
{
def assignedTo = Integer.parseInt(taskParams.assignedTo)
def priority = Integer .parseInt(taskParams.priority)
def status = Integer.parseInt(taskParams.status)
tasks = Task.createCriteria()。list {
eq(project,Project.get(taskParams。 PId))
if(assignedTo> 0)
eq(assignedTo,User.get(assignedTo))
if(priority> 0)
eq(priority,TaskPriority.get(priority) )
if(status> 0)
eq(status,TaskStatus.get(status))
}
}
返回任务
}
In my task management application, users should be able to filter tasks based on : assignedTo
, priority
, status
and/or dueDate
I am not sure on how to create a dynamic query in that it will build a query based on the available parameters.
For example :
If I have a URL such as : task/index?assignedTo=1&status=2
I can build a query based on only these two parameters. The method I am used to is the
Task.findAllByAssignedToAndStatus(
User.get(params.assignedTo),
TaskStatus.get(params.status)
)
I obviously dont want to implement a DRY method by writing out each findAllBy
query for every possible URL parameter combination.
Is there a good way to do this in grails?
I managed to get this working using createCriteria
as follows :
I am using the value 0 for any of the params if the user selects 'All' for that particular filter, therefore it will be omitted from the where clause, ie no eq()
statement for that parameter.
A snippet of the code:
else
{
def assignedTo = Integer.parseInt(taskParams.assignedTo)
def priority = Integer.parseInt(taskParams.priority)
def status = Integer.parseInt(taskParams.status)
tasks = Task.createCriteria().list {
eq("project", Project.get(taskParams.PId))
if(assignedTo > 0)
eq("assignedTo", User.get(assignedTo))
if(priority > 0)
eq("priority", TaskPriority.get(priority))
if(status > 0)
eq("status", TaskStatus.get(status))
}
}
return tasks
}
这篇关于基于传递给控制器的参数动态创建查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!