当前使用Grails 2.43。我有两个域类(州和县),以及两个针对州和县的“选择”下拉列表。
使用GORM查找器是否可以通过动态查询在选择某个州时返回该州的特定县。从而排除不在选定州内的所有其他县吗?
表单元素:
<g:select name="locationState" class="form-control" from="${....State.list().sort{it.orderNumber}}">
<g:select name="locationCounty" class="form-control" from="${...State.FindByName(it.orderNumber).counties}">
以下是示例类:
class State {
static hasMany = [county:County]
String name
String value
int orderNumber = 0
static constraints = {
name nullable:false, maxSize:50, blank:false
value nullable:false, maxSize:100, blank:false
}
String toString(){
"$value"
}
static mapping = {
table 'state'
cache: 'read-write'
columns{
id column:'id'
name column:'name'
value column:'value'
orderNumber column:'order_number'
}
id generator: 'assigned'
}
}
class County {
State state
String county
static constraints = {
state nullable:false
county nullable:false, maxSize:100, blank:false
}
String toString(){
"${state.name} - $county"
}
static mapping = {
table 'county'
cache: 'read-write'
columns{
id column:'id'
county column:'county'
state column:'state_id'
}
id generator: 'assigned'
}
}
最佳答案
这取决于您如何关联域类。如果州有许多县和/或县属于州,则可以使用动态查找器。例如:
// All Counties
County.list()
// All States
State.list()
//All Counties in State Vermont
State.findByName("Vermont").counties
//State for a county
County.findByName("Chittenden").state
如果您要制作一个动态表格,则可以先显示“州”下拉列表,然后在“州”被选中之前不激活“县”下拉列表。然后,您可以进行异步调用以获取该州的县,或者如果已经加载了完整的对象,则可以使用
selectedState.counties
填充“县”选择框。请参阅GORM对象关系映射:http://grails.org/doc/latest/guide/GORM.html#domainClasses
关于grails - GORM:可以查询州和县,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27610868/