【问题标题】:grails belongsTo map to property in another classgrails belongsTo 映射到另一个类中的属性
【发布时间】:2017-07-08 02:13:47
【问题描述】:

当子类可能属于父类中的两个属性之一(但不能同时属于两者)时,我无法理解 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 列表中的位置

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

我如何正确映射它?

提前谢谢....

【问题讨论】:

    标签: grails grails-orm


    【解决方案1】:
    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
    

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

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

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

    先生,你适合什么?

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

    假设您确实设置了从 Parent 到 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
        }
    
    }
    

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

    【讨论】:

    • 效果很好!我现在看到我不需要明确定义员工和经理的列表......因为我通过 hasMany 将他们带入课堂?谢谢!
    • 对不起,我犯了一个错误,我修复了它,简而言之,你只是获得了对父级的反向查找能力,因为松散的关系更容易管理,但失去了这种能力
    • 当然,最重要的因素是父级对 hasMany 具有可空性,否则这是一个循环,想要那个,并且因为它需要那个而不能拥有这个
    猜你喜欢
    • 2017-11-06
    • 2019-10-13
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多