我有两个表:Region
和 District
。因此,region_id
是表District
中的外键
(一个region
有一个或多个district
)。因此,当我在 list
上选择一个 region
时,我只想显示与该特定 region
关联的 districts
。
我的正确代码显示独立于 region
的所有 district
:
def list = {
params.max = Math.min(params.max? params.int('max') : 20, 100)
[districtInstanceList : District.list(params),
districtInstanceTotal: District.count()]
}
有人知道如何仅根据外键约束显示吗?我知道我可以在 list
闭包中编写一个 SQL
查询,但我想 grails 可能有办法做到这一点。
我的数据库是MySQL
,grails
版本是2.0.1
。
我的区
域是:
class District {
def scaffold = true
String name
String description
String logo
String homepage
// defines the 1:n constrain with the Region table
static belongsTo = [region : Region]
// defines the 1: constraint with the Stream table
static hasMany = [streams : Stream]
static constraints ={
name(blank:false, minSize:6, maxSize:30)
description(blank: false, maxSize:100)
}
public String toString(){
name
}
}
最佳答案
您可以使用 GORM:
def list = {
params.max = Math.min(params.max? params.int('max') : 20, 100)
Region region = Region.get(params.id) // or what parameter you're using
List districts = District.findAllByRegion(region)
[districtInstanceList : districts,
districtInstanceTotal: District.count()]
}
您可以在这里阅读有关 Grails GORM 的信息:http://grails.org/doc/latest/guide/GORM.html
关于java - 如何显示基于外键的列表 groovy grails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11371869/