6

我有一个名为 People 的 Grails 域,我想检查每个 People 是否有孩子。Childs 是其他 People 对象。这是我的域结构:

class People implements Serializable {

    static constraints = {
        name (nullable : false, unique : true)
        createdBy (nullable : false)
        creationDate (nullable : false)
    }

    static transients = ['hasChild']

    static mapping = {
        table 'PEOPLE'
        id generator: 'sequence', params : [sequence : 'SEQ_PK_ID']
        columns {
            id column : 'APEOPLE_ID'
            parentPeople column : 'PARENT_PEOPLE_ID'
        }
        parentPeople lazy : false
    }

    People parentPeople
    String name
    String description

    Boolean hasChild() {
        def childPeoples = People.createCriteria().count { 
            eq ('parentPeople', People) 
        }
        return (childPeoples > 0)
    }
}

但我不能在任何地方调用 people.hasChild() 。你能帮我解决这个问题吗?太感谢了!

4

2 回答 2

4

这是因为在 中eq ('parentPeople', People),Grails 无法理解“人”是什么(它是一个类)。您应该将“人”替换为this. 例如:

static transients = ["children"]

    def getChildren() {
        def childPeoples = People.findAllByParentPeople(this, [sort:'id',order:'asc'])
    }
于 2011-03-22T09:29:31.650 回答
0

获得相同结果的另一种方法是使用命名查询。它看起来更简洁,是专门​​为此目的而创建的。我也喜欢它,因为它符合域模型中静态声明的模式,而且它本质上是一个标准,我在整个应用程序中都使用它。当您可以声明命名查询时,声明一个瞬态然后编写一个闭包似乎有点解决方法......只是我的看法。

尝试这样的事情:

static namedQueries = {
    getChildren {
        projections {
            count "parentPeople"
        }
    }
}
于 2014-06-11T02:41:10.670 回答