grails belongsTo 映射到另一个类中的属性

标签 grails grails-orm

当子类可能属于父类中的两个属性之一(但不能同时属于两者)时,我无法理解 Grails 中的 belongsTo - hasMany 关系的概念。

例如:

class Store {
    Integer storeNumber
    List employees
    List managers

    static hasMany = [employees:Person,
                      managers:Person]
}

class Person {
    String name
    String roll

    static belongsTo = [store:Store]

    static constraints = {
        role inList: ['employee','manager']
    }
}

Person 在 Store.employees 列表或 Store.managers 列表中的位置

我收到有关“在映射中重复列...”的人的错误。我尝试了一些静态映射尝试,但仍然不明白如何正确地做到这一点。

我如何正确映射这个?

提前致谢....

最佳答案

class Store {
    Integer storeNumber
    //List employees
    //List managers

    static hasMany = [employees:Person,
                      managers:Person]
    static constraints = {
      employees(nullable:true)
      managers(nullable:true)
    }
}

class Person {
    String name
    String roll

    static belongsTo = [store:Store]

    static constraints = {
        role inList: ['employee','manager']
    }
}

现在添加一个商店
Store store = new Store(storeNumber: 1).save()
if (store) {
  Person person = new Person(name:'fred', roll:'employee', store:store).save()
  if (person) {
    store.addToEmployees(person)
  }
}

因此,头痛的收获显然是一种反向查找父级的快速方法,替代方法是下面描述的松散关系,它不关心父级,所以你不需要最后一点,显然会失去你遇到的依赖问题所以远的

结束 E2A

你需要一个有另一个关系

或者,如果您不关心 belongsTo 关系,那么事情会更容易,例如
static belongsTo = Store

那么这个因素就不再是问题了。

不同之处在于您拥有的当前方法与我向您展示的后者 - 如果查询是从 child 开始的,您可以轻松地从 child 反向走回 parent

无论哪种方式,您都可以始终从父级开始查询,然后加入子级并查找子级

先生,您适合什么

最终编辑
您知道,当您多年来一直在做这些事情时,您会找到以其他方式做事的方法:

假设您确实设置了从父级到子级的松散/弱引用,并且您想要访问父级。方法如下:
Class User {
     String username
    static hasMany=[childs:Children]
}

Class Children {
    String firstName
    static belongsTo=User

   // now to get access back to parent user without knowing parent a hackish thing like this can be done:

    User getUser() {
        User.findByChilds(this)
    }
    String getUserName() {
        return user?.username
    }

}

现在从一个 child 你可以做 ${instance.user} 或 ${instance.userName} 这将绑定(bind)回父对象并通过子对象本身找到 findByChilds(this)几年前,我猜这会扭曲我

关于grails belongsTo 映射到另一个类中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42316788/

相关文章:

Grails 命令对象 - 是否有通用模式?

grails - 在链接中传递参数-Grails

mysql - Grails 子查询

Grails + 斯波克 : NullPointerException when doing addTo* on an embedded hasMany field

unit-testing - PageRenderer 在单元测试期间返回空对象

jquery - 使用 REST 发布对象数组的规范技术

grails - junit.framework.AssertionFailedError : No more calls to 'scp' expected at this point.需求结束。

Grails3 + mysql不使用 Camel 表示法创建表名和列名

grails-orm - 域对象上的“请求的 bean 当前正在创建中”