代码之家  ›  专栏  ›  技术社区  ›  bsr

域类(grails)中的包含关系

  •  0
  • bsr  · 技术社区  · 14 年前

    I'm not sure whether it is the right terminology for this kind of relationship, so please correct me. I need to define a domain class, which maps to a table in the database. The class needs to define a hierarchy of relationships of the same type. For eg, say I need to model the below roles with the same class 行政经理经理主管助理等。

    class RoleType {
        String roleName
        String description
    
        static hasMany = [parentType: RoleType]
    }
    

    so, through the parenttype, I may be able to define the hierarchy. Note that it is not inheritance. I may also define 1:m relationship towards the immediate child aswell. Now, how easily I can find the contained objects. For eg, if I need to find all the roles below Manager (say, Supervisor, Associate), or under supervisor (associate) etc. I use Grails.

    谢谢。

    1 回复  |  直到 14 年前
        1
  •  1
  •   Community CDub    7 年前

    定义关系

    What you're defining is a unidirectional one-to-many, with the parent being the 'owner' of the relationship. If you define it like this:

    class RoleType {
        String roleName
        String description
        static hasMany = [children: RoleType]
    }
    

    然后你可以这样做:

    def superManager = new RoleType(roleName: 'SuperManager')
    def manager = new RoleType(roleName: 'Manager')
    
    superManager.addToChildren(manager);
    

    或者我相信你也可以这样速记:

    def superManager = new RoleType(roleName: 'SuperManager').addToChildren(roleName: 'Manager').save()
    

    通过定义与 [children: RoleType] ,Grails在名为 children that you can access like any other property, e.g. myRole.children.each { it.doSomething() } .

    To make it easier to work with, you could also make the relationship bidirectional by adding the following property:

    RoleType parent
    

    如果你使用动态 addTo* methods, they should ensure that both ends of the relationship get their properties correctly set. 看一看 this 供参考。

    正在检索所有后代

    你在这里有一些选择,但我不认为有一种内置的方式可以自动完成。

    一种选择是编写自己的递归或迭代方法,来获取和收集所有子级。可以找到一个这样的例子 here .

    Alternatively, if you execute this method a lot and it become a bottleneck, you could do some manual manipulation of your database. You might have triggers that operate on inserts and updates in your RoleType table that maintain lists of implicit relationships between all RoleTypes.

    例如,如果创建 RoleType A -gt; RoleType B -gt; RoleType C 关系,触发器可能(在单独的表中)创建 罗德利普A -gt; 罗莱佩B , 罗德利普A -gt; 罗德利普C 罗莱佩B -gt; 罗德利普C 关系。You could then query this table by a single parent and get all of its implied children/descendants. I've seen this done for complex ACL processing.