代码之家  ›  专栏  ›  技术社区  ›  Pablo Mosby

逐子查找父一对多关系Grails

  •  0
  • Pablo Mosby  · 技术社区  · 7 年前

    我有以下课程:

    class Parent{
        static hasMany = [children:Child]
    }
    
    class Children{
        static belongsTo = [Parent]
    }
    

    我想做一些像

    Parent.findByChildren(ChildInstance)
    

    但这不起作用,哪种方法合适?

    2 回复  |  直到 7 年前
        1
  •  1
  •   bassmartin    7 年前

    将您的孩子的班级改为以下条款:

    class Children{
        static belongsTo = [parent: Parent]
    }
    

    childInstance.parent

        2
  •  0
  •   elixir    7 年前

    首先,我要将Children域中的关系更改为

    static belongsTo = [parent: Parent]  // suggested by @bassmartin
    

    Parent parent
    

    两者都做相同的事情。

    ChildInstance.parent     // returns instance of parent
    

    类似地,如果你想找到父母的所有孩子,你可以这样做

    parent.children          // return an array of children which you can iterate over.