我有一个一对多的关系:
class Author {
String name
static hasMany = [books:Book]
static constraints = {
}
}
class Book {
String name
static belongsTo = [author:Author]
static constraints = {
}
}
我希望能够计算属于作者类中作者的书籍数量,这样生成的 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 必须保存在数据库中。
最佳答案
如果您不想将所有子项从数据库中拉出并对其进行计数(这可能对非常大的数据集不利),则另一种方法是在父类上使用这样的方法。
def numberOfChildren()
{
def result = Child.executeQuery("select count(*) from Child where parent = :parent", ["parent":this])
def resultCount = result[0]
return resultCount
}
关于Grails 计算域类中一对多的子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24616116/