2013-05-22 92 views
0

我有一个Section域,看起来像这样。我从它建立导航和下段或子段顺序的故事,例如:新闻中心>犯罪>火车大劫案查询grails树对象

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 
    } 
} 

,看起来像这样

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个节:

首页,新闻,体育,旅游,科技,文化和评论,并与家庭之外,他们都有孩子部分

如:新闻都会有LEVE l下面包含英国,欧洲,美国,然后美国可以有另一层儿童部分包含政治和犯罪部分。如上所述的故事存储在部分下。因此,一个故事“奥巴马Impeached”将作为其发布价值
新闻>美国>政治

我必须编写一个查询,它将获得n个故事,这些故事存储在顶级部分的其中一个子节点下。因此,如果我通过“新闻”部分作为参数(可能没有任何故事直接存储在“新闻”下,但可能存在新闻>英国>犯罪)我想返回存储在任何子区段下的故事“新闻”

我该怎么做gorm?我应该使用HQL吗?我仍然是一个小白,所以任何帮助,将不胜感激。

回答

1

你可以有这样一个简单的解决方案:

首先,要加快速度,我想有一个树节在内存缓存。当你启动应用程序,您可以创建此树并将其存储在一个applicatin方面: 在的grails-app/conf目录/ BootStrap.grrovy,你可以做这里面的init关闭

def init = { servletContext -> 
    servletContext.sectionsTree = something 
} 

为了创建这个“东西”,你可以递归遍历部分儿童和构建包含每一部分的所有children's 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包含从部分儿童的所有ID和儿童的孩子。

所以,现在,你可以执行一个简单的HQL查询来获取Section's故事:

Story.executeQuery("select s from Story s where s.publishUnder.id in (?)", [childrenIds]); 

那只是一个解决方案.... SE你想想看。

Cheers

+0

谢谢felipenasc。我会尽快回复你。我没有这样想过。 – Bill

+0

嗨对不起,我已经离开了。 – Bill

+0

嗨菲利普我无法让代码工作,因为我想。然而,我解决了它通过添加一个rootNode属性的部分域,然后使用'Story.where(publishUnder.rootNode = sectionRoot)'其中sectionRoot等于'新闻'或'体育'等。感谢您抽出时间回答。 – Bill