关系多对一如何保存

时间:2014-04-02 22:03:23

标签: grails gorm

我在谷歌搜索过,大多数例子没有帮助,或者我做错了我想做的事情。所以我不太了解GORM如何在这种关系中保存,我如何保存与用户相关的新事件? addToEvent无效。

class User{
Long id
String name
Long codeUser
StatusType statusType
static hasMany = [event: Event]
static constraints = {
    statusType(nullable: true)
    name(nullable: true)
}
class Event{
Long id
String name
String startDate
String description
static belongsTo = [user:User]
static constraints = {
    name(nullable: true)
    startDate(nullable: true)
    description(nullable: true)
}

def createEvent(){
    def data = JSON.parse(params.data)
    def user = User.findByCodeUser(data.codeUser)
    def event = new Event(name: data.name, startDate: data.start_time, description: data.description)
    //removed the user: user
    user.addToEvent(event)
    user.save(flush: true)
}

错误是:Message: No signature of method: java.util.ArrayList.addToEvent() is applicable for argument types: (project.web.Event) values: [project.web.Event : (unsaved)]

1 个答案:

答案 0 :(得分:0)

Grails documentation所述,您需要使用addTo *方法通过GORM正确保存关系。

class User{
    ...//attributes
    Long codeUser
    static hasMany = [event: Event]
}
class Event{
    ...//attributes
    Long codeEvent
    static belongsTo = [user:User]
}

def user = User.findByCodeUser(params.codeUser)

def event = new Event(codeEvent: params.codeEvent)
user.addToEvent(event)
user.save(flush: true)

请注意,您不必设置User的{​​{1}}属性,保存Event也会保存User

最后,作为样式指南,您通常希望以复数形式命名您的馆藏。

Event