【问题标题】:Querying GORM association查询 GORM 关联
【发布时间】:2011-11-18 11:54:11
【问题描述】:

我想构建一个非常简单的帮助台应用程序来学习 grails。我希望用户能够登录,创建请求/事件。 用户选择产品线、该产品线的主题和该主题的子主题。每个子主题都有一个或多个对其负责的支持用户。 另一方面,支持用户可以查看属于他“管辖范围”的事件列表。我的域类看起来像这样:

class Request{  


Date dateCreated
String subject
String startedBy 
String description
String status
String priority 
Productline productline
Topic topic
Subtopic subtopic


static constraints = {
    //id unique: true
    dateCreated(blank:true,nullable:true)
    subject()
    description(maxSize:5000)
    status (blank:true,nullable:true)
    priority(inList:["Normalan","Hitno","Nije hitno"])
    productline(blank:true,nullable:true)
    topic(blank:true,nullable:true)
    subtopic(blank:true,nullable:true)
    company(blank:true,nullable:true)
    contact(blank:true,nullable:true)
    startedBy(blank:true,nullable:true)
    acceptedBy(blank:true,nullable:true)
}

}

类子主题{

String subtopic
Productline productline 
Topic topic


static hasMany = [responsibilities: Responsibility]


String toString(){
    "$subtopic"
}
static constraints = {
    subtopic()
    productline()
    topic()
}

List contacts(){
    return responsibilities.collect{it.contact}
}

List addToContacts(Contact contact){
    Responsibility.link(contacts, this)
    return contacts()
}

List removeFromContacts(Contact contact){
    Responsibility.unlink(contact, this)
    return contacts()
}

}

class Responsibility {

Contact contact
Subtopic subtopic

static Responsibility link(contact, subtopic){
    def r = Responsibility.findByContactAndSubtopic(contact, subtopic)
    if(!r){
        r = new Responsibility()
        contact?.addToResponsibilities(r)
        subtopic?.addToResponsibilities(r)
    }
    return r
}

static void unlink(contact, subtopic){
    def r = Responsibility.findByContactAndSubtopic(contact, subtopic)
    if(r){
        contact?.removeFromResponsibilities(r)
        subtopic?.removeFromResponsibilities(r)
        r.delete()
    }
}

static constraints = {
}

}

class User {

transient springSecurityService

String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired

String toString(){
    "$username"
}


static constraints = {
    username blank: false, unique: true
    password blank: false
}

static mapping = {
    password column: '`password`'
}

Set<Role> getAuthorities() {
    UserRole.findAllByUser(this).collect { it.role } as Set
}

def beforeInsert() {
    encodePassword()
}

def beforeUpdate() {
    if (isDirty('password')) {
        encodePassword()
    }
}

protected void encodePassword() {
    password = springSecurityService.encodePassword(password)
}

}

class Contact {

String realname
String company
String mobile
String fix
String email
User user

String toString(){
    "$realname"
}

static hasMany = [responsibilities: Responsibility]

static constraints = {
}

List subtopics(){
    return responsibilities.collect{it.subtopic}
}

List addToSubtopics(Subtopic subtopic){
    Responsibility.link(this, subtopic)
    return subtopics()
}

List removeFromSubtopics(Subtopic subtopic){
    Responsibility.unlink(this, subtopic)
    return subtopics()
}

}

在我的 RequestController 中,我有 supportList() 操作。成功登录后,角色 ROLE_SUPPORT 的用户将被发送到此操作,该操作应过滤数据,因此发送到查看的唯一请求实例是当前登录用户负责的请求实例。这是行动:

def supportList = {

    def contact = Contact.findByUser(springSecurityService.currentUser)
    def requestList = contact.subtopics().collect {Request.findAllBySubtopic(it)}

    params.max = Math.min(params.max ? params.int('max') : 10, 100)
    [requestInstanceList: requestList, requestInstanceTotal: requestList.count()]
}

我的桌子空了。实际上,我得到了预期的行数,但所有字段都是空的。我究竟做错了什么?

这是我的普惠制:

<%@ page import="com.testapp.Request" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="layout" content="main" />
        <g:set var="entityName" value="${message(code: 'request.label', default: 'Request')}" />
        <title><g:message code="default.list.label" args="[entityName]" /></title>
    </head>
    <body>
        <div class="nav">
            <span class="menuButton"><g:link class="create" action="create">
                <g:message code="default.new.label" args="[entityName]" /></g:link></span>
        </div>
        <div class="body">
            <h1>Lista Zahteva</h1>
            <g:if test="${flash.message}">
            <div class="message">${flash.message}</div>
            </g:if>
            <div class="list">
                <table>
                    <thead>
                        <tr>

                            <g:sortableColumn property="id" 
                                title="${message(code:   'request.id.label', default: 'Id')}" />

                            <g:sortableColumn property="subject" title="Datum kreiranja" />

                            <g:sortableColumn property="subject" title="Tema" />

                            <g:sortableColumn property="priority" title="Prioritet" />

                            <th><g:message code="incident.startedBy" default="Započeo" /></th>

                            <g:sortableColumn property="status" title="Status" />

                        </tr>
                    </thead>
                    <tbody>
                    <g:each in="${requestInstanceList}" status="i" var="requestInstance">
                        <tr class="${(i % 2) == 0 ? 'odd' : 'even'}">

                            <td><g:link action="show" id="${requestInstance.id}">
                                ${fieldValue(bean: requestInstance, field: "id")}</g:link></td>

                            <td width="200">${fieldValue(bean:requestInstance,field:"dateCreated")}</td>

                            <td width="200">${fieldValue(bean: requestInstance, field: "subject")}</td>

                            <td width="200">${fieldValue(bean: requestInstance, field: "priority")}</td>

                            <td width="200">${fieldValue(bean: requestInstance, field: "startedBy")}</td>

                            <td width="200">${fieldValue(bean: requestInstance, field: "status")}</td>

                        </tr>
                    </g:each>
                    </tbody>
                </table>
            </div>
            <div class="paginateButtons">
                <g:paginate total="${requestInstanceTotal}" />
            </div>
        </div>
    </body>
</html>

【问题讨论】:

    标签: grails grails-orm


    【解决方案1】:

    使用您当前的模型,您可以像这样查询当前用户职责:

    Responsability.findAllBySupport(springSecurityService.currentUser).
        collect {Incident.findAllBySubtopic(it.subtopic)}.flatten()
    

    事实上,Responsability 只是用户和子主题之间的连接表。如果您将其删除,并在用户和子主题之间定义了多对多关系:

    class User {
        static hasMany = [supportedSubtopics: Subtopic]
        ...
    }
    
    class SubTopic {
        static hasMany = [supportingUsers: User]
        ....
    }
    

    你可以这样查询:

    springSecurityService.currentUser.supportedSubtopics.collect {Incidents.findBySubtopic(it)}.flatten()
    

    通过将hasMany = [incidents: Incident] 添加到子主题中,您可以进一步将其简化为

    springSecurityService.currentUser.supportedSubtopics*.incidents.flatten()
    

    【讨论】:

    • 如果我在用户和子主题之间定义多对多关系,将用户添加到子主题看起来像这样:subtopic.AddToUsers(someUser)?
    • 另外,是否需要定义子主题和用户之间的父子关系?
    • 1) 是的,添加看起来像这样。 2)它不是真正的父子,因为在任何一个类中都没有指定belongsTo。如果您在子主题中省略 hasMany,Grails 会将关系视为一对多。我不确定它会带来什么,因为它仍然会使用连接表来映射关系。
    • 我已经编辑了我的域模型并添加了一些逻辑。可以查一下吗?
    • 请粘贴您的 GSP。当您说“我得到了预期的行数”时,您是指 requestInstanceList 还是 requestInstanceTotal
    猜你喜欢
    • 2015-04-30
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    相关资源
    最近更新 更多