簡體   English   中英

在同一個域類上多對多

[英]Grails many-to-many on the same domain class

我想建立一個既有孩子又有父母的“實體”類:

class Entity {
    static hasMany [childs: Entity, parents: Entity]
}

但是我不知道如何映射我的數據(我應該使用mapledBy嗎?)

我的測試:

@Test
void testEntityCanHaveAChild() {
    Entityparent = new Entity()
    Entitychild = new Entity()

    parent.addToChilds(child)

    assert parent.childs
    assert parent.childs.size() == 1
    assert parent.childs.contains(child)

    assert child.parents
    assert child.parents.size() == 1
    assert child.parents.contains(parent)
}

所以我想從父母那里得到所有孩子,而我想從孩子那里得到所有父母

你不能那樣做。

在一對多關聯中,外鍵被放入“一個”部分。

現在從您的示例中我了解到,如果人x是人y的孩子,那並不意味着人y是人x的父母嗎? x人可以有父母:z人和t人?

我將首先討論以下情況:人x只能有一個父母,並且如果x是y的孩子,那么y是x的父母。

對於這種情況,我將添加一個默認值為null的新列parent_id,並只說hasMany [children:Person]和belongsTo [parent:Person]這可以解決一個孩子只能有一個父母的情況。

對於另一種情況,當一個孩子可以有多個父母並且不必一定要讓某人的孩子成為該孩子的父母時,有兩種選擇:1. db列中的ID列表(我不喜歡在關系數據庫中這樣) ,但在NoSQL中是可以接受的)。2.連接table(2)。 這可以是一個多態連接表,2個連接表或一個具有3列的連接表,其中一個始終為空。 然后,您需要向所有部分添加belongsTo。 並手動設置聯接表的映射。 就像是:

   static mapping = {
   hasMany joinTable: [name: 'parent_child_connection',
                       key: 'person_id',
                       column: 'parent_id']
}

編輯:添加addToChilds

我要做的是介紹另一個域,例如ParentChild

class ParentChild {
    Person parent
    Person child 
}

然后修改人

class Person {
def parents() {
    ParentChild.executeQuery("select pc.parent from ParentChild pc where pc.child = :child", [child:this])
}

def children() {
    ParentChild.executeQuery("select pc.child from ParentChild pc where pc.parent = :parent", [parent:this])
}
def addToChilds(Person child){
    New ParentChild(parent:this, child:child).save()
}
}

抱歉,我只熟悉HQL。 不確定如何以更干凈的方式執行此操作

我發現做到這一點的唯一方法是在“兩個表”之間添加多對多表並模擬“自動關系”,如下所示:

class EntityBound {
    Entity parent
    Entity child 
}

class Entity {
    static hasMany [bounds: EntityBound]


    def childs() {
        EntityBound.findAllByParent(this).collect{ it.child }
    }

    def parents() {
        EntityBound.findAllByChild(this).collect{ it.parent }
    }

    Entity addChild(Entity entity){
        addToBounds(new EntityBound(parent:this, child:child))
        return this
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM