grails - GORM:可以查询州和县

标签 grails gorm

当前使用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/

相关文章:

validation - Grails项目中集成测试的Spock验证问题

grails - 嵌入式Grails SQL View

grails - 如何提取 grails 对象中的第一个值

mongodb - 无法在 Grails 中使用 gmongo 插入唯一文档

unit-testing - 在grails单元测试中访问resources.xml/appContext.xml定义的bean

grails - 使用复合ID时多个hasMany与同一个域类有关系的问题

grails - 生成由Grails AssetPipeline处理的资源的URL

sql - 如果列中有日期和时间,如何检查当前日期?

grails - Grails是否可以确保在请求中的调用之间重用数据源连接?