如何在grails中保存多个包含2个以上列的子值

时间:2014-08-26 12:37:38

标签: mysql grails grails-2.0 grails-domain-class grails-controller

我有一个名为委员会的域名,是父母。另一个领域是委员会成员,而且是孩子。

 class Committee {
    Long id
    Division division
    District district
    Upazila upazila
    UnionParishad unionParishad
    Ward ward
    CommitteeType committeeType
    String name
    int memberAmount
    Date entryDate=new Date()
}

class CommitteeMembers {
    Committee committee
    CommitteeMemberDesignation committeeMemberDesignation
    String name
    String address
    String mobileNo
    String  email
}

现在我需要将一个委员会的成员保存到数据库中:

 def addNewCommitteeAndMembers(){
    Committee committee = new Committee()
    committee.division = Division.get(params.divisionId?.toLong())
    committee.district = District.get(params.districtId?.toLong())
    committee.name = params.wcName
    committee.presidentName = params.presidentName
    committee.unionParishad = UnionParishad.get(params.upId?.toLong())
    committee.upazila = Upazila.get(params.upazilaId?.toLong())
    committee.ward = Ward.get(params.wardId?.toLong())

    List memberNames = params.list('memberName')
    committee.memberAmount = memberNames.size()

    committee.save()

    def committeeId = Committee.get(committee.id)
    memberNames.each {
        CommitteeMembers committeeMembers = new CommitteeMembers()
        committeeMembers.name = it
        committeeMembers.committee = committeeId
        committeeMembers.save()
    }

    message = "Committee & Members are saved successfully"
}

但是我的委员会正在保存,但我怎样才能保存我的委员会成员的价值观。假设我在委员会成员中有2个字段作为姓名和地址。

我现在如何用委员会ID保存这两个字段?我不知道该怎么做。我为这么多委员会成员只保存了一个字段但不超过1个字段。

我已经尝试了很多,并且为此付出了很大的代价。但没有积极的结果。有人可以帮我这个吗?

2 个答案:

答案 0 :(得分:1)

没有域类很难回答,但我认为您有以下域类:

class Committee {
    ...
    static hasMany = [members: CommitteeMembers]
    ...
}

class CommitteeMember {
    String name

    static belongsTo = [committee: Committee]
}   

在这种情况下,要保留Committee N CommitteeMembers,您必须:

def committee = new Committee()
// Set all the fields in Committee
committe.name = ...
committe.district = ...
...

List memberNames = params.list('memberName')
memberNames.each { String memberName ->
    def committeeMember = new CommitteeMember()
    committeeMember.name = memberName

    committee.addToMembers(committeeMember)
}

committee.save()

请注意,您只需将成员添加到committe,然后保存committe。你不必保存每个成员。 Grails将为您做到这一点。

答案 1 :(得分:1)

使用刷新保存您的委员会对象:

committee.save flush:true

然后不要从数据库加载它并保存成员:

memberNames.each {
    CommitteeMembers committeeMembers = new CommitteeMembers( name:it, committee:committee )
    if( !committeeMembers.save() ) log.warn "save failed: $committeeMembers.errors"
}

PS。在PLURAL中被称为委员会成员的班级?!