我有一个看起来像这样的Section域。我从中构建导航,并在部分或子部分下订购故事,例如:新闻>犯罪>火车大劫案
class Section {
String name;
String path
Section parent;
Boolean active = true;
int level = 0;
Boolean isRoot = false;
static hasMany = [children:Section]
static mappedBy = [children:'parent']
static mapping = {
parent :'all-delete-orphan'
parent lazy:true
}
}
看起来像这样的Story域
class Story
{
String title;
String story;
List link;
List substory;
List picture;
Section publishUnder
boolean parent = false;
boolean approved = false;
Date dateCreated;
Date lastUpdated;
static belongsTo = [author:Author]
static hasMany=
[
link:String,
substory:Story,
picture:Picture
]
}
我们有7个根部分:
家庭,新闻,体育,旅游,科技,文化和评论,除了家庭以外,其他所有子类别
例如:新闻将在其以下级别包含英国,欧洲和美国,然后美国可能在子级别中包含政治和犯罪部分。如上所述的故事存储在“部分”下。因此,一个故事“被弹story的奥巴马”的值(value)将不大
新闻>美国>政治。
我必须编写一个查询,该查询将获取n个故事,这些故事存储在顶级部分的子项之一下。因此,如果我将“新闻”部分作为参数传递(可能没有直接在“新闻”下存储的故事,但是可能在新闻>英国>犯罪下)我想返回存储在任何子部分下的故事“新闻”
我该如何使用gorm?我应该使用HQL吗?我还是这个菜鸟,任何帮助将不胜感激。
最佳答案
您可以有一个简单的解决方案,如下所示:
首先,为了加快速度,我将在内存缓存中添加一个Sections Tree。启动应用程序时,可以创建此树并将其存储在应用上下文中:
在grails-app / conf / BootStrap.grrovy中,您可以在init闭包中执行此操作
def init = { servletContext ->
servletContext.sectionsTree = something
}
要创建此“内容”,您可以递归地遍历子节,并构造一个列表或 map ,其中包含每个节的所有子节的ID。类似:
rootSections = [[section:root1, childrenIds:[23,45,67,89,5,43,45,6,7,87], children:[section:child1, childrenIds:[23,45,67]]], [section:root2, childrenIds:[32,43,54,65,76], children:[]]]
其中childrenIds包含child和child子节中的所有ID。
因此,现在,您可以执行一个简单的HQL查询以获取该部分的故事:
Story.executeQuery("select s from Story s where s.publishUnder.id in (?)", [childrenIds]);
那只是一种解决方案。...就是您对此的看法。
干杯
关于grails - 查询grails树对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16688715/