2017-10-11 71 views
0

使用域实例Grails中查找子域,我怎么找到的子域使用域实例Grails中

让说,我有

class Family { 
    Integer id 
    Parent parent 
} 


class Parent { 
    Interger id 
    static hasMany = [children: Child] 
} 

class Child { 
    String name 
} 

所以在控制器,

Parent mom = Family.findById(1).parent 

所以现在,如何使用mom在父母中获得name == "Child"的孩子?
它甚至有可能吗?

回答

0

我认为这应该工作。

Child child = mom.children.find { it.name == 'child' } 

但我不建议使用这种查询。 Grails有很多查询方法,您可以在这里阅读http://gorm.grails.org/latest/hibernate/manual/index.html#querying。我还向您推荐本指南http://guides.grails.org/querying-gorm-dynamic-finders/guide/index.html其关于动态查找器的问题,与使用常规采集方法进行查询的查询不同。

我希望它的帮助下充分

+0

这在这个特定情况下适用于我,但我会牢记这些文档。谢谢 – StrandedHere

0

可以使用criteria API为:

Parent.withCriteria { 
    children { 
     eq("name", "Bob") 
    } 
} 

在这个例子中children将被连接到parent。所有的父母都会被退回,有一个叫做“鲍勃”的孩子。

0

您可以简单地使用封闭的findAll {}这样:

def childrenList=mom.findAll{it.children.each{ 
        if(it.name=='child') 
         return it 
        } 
        } 

这会给你的名字“儿童”对象所有孩子的名单。

0

正如@ user615274所建议的,接受的解决方案有效,但可能会有性能问题。

Grails闪耀的一个特征是动态查询。我会修改子域并使用动态查询。例如。

由于父母“的hasMany”关系到孩子,孩子“属于关联”父

class Child { 
    String name 

    Parent parent 
    // or static belongsTo = [parent:Parent] 
} 

一旦这种关系建立,那么你可以使用动态查询

def child = Child.findByParent(mom) // return the first matching result 
def children = Child.findAllByParent(mom) // returns a list of matching result 

我希望这有助于。

+0

我明白,属于也会工作,但在这种特殊情况下,我需要一种方法来提取信息而不必更改域,谢谢。 – StrandedHere