Grails统计域类中一对多的子类
我有一对多的关系:Grails统计域类中一对多的子类,grails,gorm,Grails,Gorm,我有一对多的关系: class Author { String name static hasMany = [books:Book] static constraints = { } } class Book { String name static belongsTo = [author:Author] static constraints = { } } 我希望能够计算author类中属于作者的书籍数量,这样生成的MySQL
class Author {
String name
static hasMany = [books:Book]
static constraints = {
}
}
class Book {
String name
static belongsTo = [author:Author]
static constraints = {
}
}
我希望能够计算author类中属于作者的书籍数量,这样生成的MySQL表如下所示:
id | version | name | bookcount
-- | ------- | ---- | ---------
1 | 0 | foo | 15
2 | 0 | bar | 3
3 | 0 | baz | 7
…其中bookcount是作者类中定义的字段:
class Author {
String name
int bookcount = ??
static constraints = {
}
}
编辑1:
bookcount必须持久保存在数据库中。您可以使用执行以下操作: 在数据库中更新对象之前,将调用
beforeUpdate
方法
getBookCount()
属性getter确保我们始终获得正确的值。如果在添加更多的Book
s后作者尚未保存,bookCount
将不会是最新的,直到作者save()
d
如果我们不使用代码中的bookCount
,我们可以内联它
def "explicitly persist book count" () {
given:
Author author = new Author(name:'author')
author.save (failOnError: true)
when:
author.addToBooks (new Book(name:'book'))
author.save (failOnError: true, flush: true)
then:
author.bookCount == 1
author.@bookCount == 1
}
如果您不想从数据库中取出所有子项并对它们进行计数(这可能对非常大的数据集有害),另一种方法是在父类上使用类似的方法
def numberOfChildren()
{
def result = Child.executeQuery("select count(*) from Child where parent = :parent", ["parent":this])
def resultCount = result[0]
return resultCount
}
是否需要将此值保存在数据库中?或者你只需要另一种方法来计算这个值?是的。对我来说,“bookcount”是Author的一个属性很重要,这样就可以使用authoristance.bookcount之类的东西访问它。您还可以通过Author类中名为
getBookCount
的方法来获取bookcount
,无论您想在controller中做什么。例如,Integer getBookCount(){Book.countByAuthor(this)}
。您有很多可能性:瞬态属性(不在数据库中持久化),或者类似于bookcount=author.Book?author.book.size():0,或使用拦截器增加实字段中的值(此字段将是数据库中的实字段)。如果不需要将值保存在数据库中,此链接将帮助您:(实现与dmahapatro的注释中相同)
def numberOfChildren()
{
def result = Child.executeQuery("select count(*) from Child where parent = :parent", ["parent":this])
def resultCount = result[0]
return resultCount
}