Grails GORM Mongo hasMany关联未保存

时间:2018-06-20 00:18:06

标签: mongodb grails groovy gorm

我有一个具有一对多关联的域类。看起来像这样:

class FormResponse {

    static String DRAFT = 'Draft'
    static String SUBMITTED = 'Submitted'
    static String REJECTED = 'Rejected'
    static String APPROVED = 'Approved'

    static mapWith = "mongo"

    ObjectId id
    Date dateCreated
    Date lastUpdated
    User createdBy
    User updatedBy
    Form form
    String currentStatus = DRAFT
    List<FormSectionResponse> formSectionResponses
    List<FormResponseComment> formResponseComments

    static hasMany = [ formSectionResponses: FormSectionResponse, formResponseComments: FormResponseComment ]

    static mapping = {
    }

    static constraints = {
        updatedBy nullable: true
    }

}

FormResponseComment的域类:

class FormResponseComment {

    static mapWith = "mongo"

    ObjectId id
    Date dateCreated
    Date lastUpdated
    User createdBy
    String comment

    static belongsTo = [FormResponse]

    static mapping = {
    }

    static constraints = {
    }

}

我有一个保存该对象的控制器方法,如下所示:

def saveFormResponse(FormResponse formResponse) {
   def saved = formService.saveFormResponse(formResponse)
   respond(saved)
}

以及服务方法:

def saveFormResponse(response) {
    return response.save(flush: true, failOnError: true)
}

当我发布到该方法时,我可以看到formResponseComments列表按预期的方式填充:

enter image description here

并保存FormResponseComment:

enter image description here

但是FormResponse对象没有收到与子FormResponseComment的关联:

enter image description here

那为什么这里没有建立联系?

Grails 3.3.3

1 个答案:

答案 0 :(得分:1)

通过向FormResponseComment域类添加反向引用来解决,如下所示:

static belongsTo = [formResponse: FormResponse]