简体   繁体   English

在两个域对象上一对一地学习

[英]Grails one to one on two domain object

I want to add a child to two different parent class, like that: 我想将一个孩子添加到两个不同的父类中,如下所示:

First: 第一:

class Member {
    Profile profile

    Member() {
        this.profile = new Profile()
    }

    static mapping = {
        profile cascade: 'all-delete-orphan'
    }
}

Second: 第二:

class Team {
    Profile profile

    Team() {
        this.profile = new Profile()
    }

    static mapping = {
        profile cascade: 'all-delete-orphan'
    }
}

Thw child is simply define like that 孩子就是这样定义的

  class Profile() {
  }

The probleme is when I save the parent, it dosent save the child: 问题是当我保存父母时,它不保存孩子:

Member member = new Member().save(flush: true, failOnError: true)

assert !member.hasErrors()
assert member.profile           
assert !member.profile.hasErrors()

assert member.profile.id //FAIL

What do I do wrong? 我做错了什么? Is there a better way to do it? 有更好的方法吗?

UPDATE: 更新:

I found this 我找到了这个

Saving associated domain classes in Grails 在Grails中保存关联的域类

It seem that 'belong to' is needed for that kind of behavior. 这种行为似乎需要“属于”。 But Why the 'cascade: 'all-delete-orphan' doesn't force this ? 但是,为什么“级联:'全部删除-孤儿'”不强制这样做呢? Because I can't use 'belong to' in that specific case 因为在那种情况下我不能使用“属于”

I copied your example (with slight modification to change group table name to a non-reserved word) and the cascades are working properly using grails 2.2.1. 我复制了您的示例(稍作修改即可将组表名称更改为非保留字),并且使用grails 2.2.1可以使级联正常工作。 Both Member and Group cascaded their saves to the newly created Profiles . MemberGroup其保存级联到新创建的Profiles

Assuming your classes are more complicated than this, you might have an error elsewhere in your class (eg cascade behavior described in constraints instead of mapping , etc). 假设您的类比这更复杂,则您在类中的其他地方可能会有错误(例如,在constraints描述的级联行为,而不是mapping等)。

I found a nice solution. 我找到了一个不错的解决方案。 The best was to define both parent in the child but nullable. 最好是在孩子中定义两个父对象,但都可以为空。 Like that: 像那样:

class Profile() {
    static belongsTo = [member: Member, team: Team]

    static constraints = {
        member nullable: true
        team nullable: true
    }
}

This way, the cascade behavior work just fine ! 这样,级联行为就可以了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM