我正在使用Grails 1.3.7。假设我有域对象 Foo 和 Bar 。 Foo 和 Bar 都有一个 Noodle 实例列表。在 NoodleController , FooController 和 BarController 中,我有一个 fetchNoodles 动作,它返回一个JSON记录列表,如此
NoodleController
def fetchNoodles = {
List data = []
for(noodle in Noodle.list())
data.add([noodle.id, noodle.name, noodle.stuff]
render data as JSON
}
FooController的
def fetchNoodles = {
List data = []
foo = Foo.get(params.id)
if (foo) {
for(noodle in foo.noodles())
data.add([noodle.id, noodle.name, noodle.stuff]
}
render data as JSON
}
BarController
def fetchNoodles = {
List data = []
bar = Bar.get(params.id)
if (bar) {
for(noodle in bar.noodles())
data.add([noodle.id, noodle.name, noodle.stuff]
}
render data as JSON
}
问题
答案 0 :(得分:1)
将其移至NoodleService
。然后,在BarController
中,按照
def noodleService
def fetchNoodles = {
List data = noodleService.getNoodles(Bar.get(params.id)?.noodles)
render data as JSON
}
或
noodleService.getNoodles(Bar.get(params.id)?.noodles, { it.name =~ /A.+/ }))
如果我们在检索noodles
集合后谈论过滤。如果您需要在数据库级别上过滤noodles
,则需要以不同方式访问它们,例如:
noodleService.getNoodles([barId: params.id], params.subMap(
['order', 'sort', 'max', 'offset', 'whatever-filter-field-names-here']))
并在NoodleService.getNoodles(Map criteriaFields, Map filterFields)
查询noodles
中使用条件。