2010-01-06 40 views
0
Article { 
    String categoryName 
    static hasMany = [ 
     tags: Tag 
    ] 
} 

Tag { 
    String name 
} 

現在我想查找所有相關文章的列表。相關含義,與myArticle具有相同類別名稱的所有文章或與myArtcle具有相同標籤的所有文章。Groovy在Grails中的做法

只有匹配的categoryName,這裏是我將如何使用閉包獲取relatedArticles。

def relatedArticles = Article.list().find {it.categoryName == myArticle.categoryName } 

任何人都希望通過CategoryName或Tag Name(以常規方式)查找所有文章?

任何使用Criteria或自定義查詢的解決方案也是值得讚賞的。

回答

1

這會工作:

def myArticle = // the article you want to match 

def relatedArticles = Article.list().findAll { 
    (it.categoryName == myArticle.categoryName || 
      it.tags.name.intersect(myArticle.tags.name)) && 
      it.id != myArticle.id)    
} 

但是,如果你有一個相當大的數量的物品,只有在預期當中的少數與之相匹配的是效率極其低下的,因爲這將加載所有的文章,然後遍歷它們都在尋找匹配。

一種更好的方式是簡單地寫,只有負載匹配的文章(而不是調用Article.list()

+0

就性能問題達成一致。我只有大約50篇文章,它不會增加太多。 – Langali 2010-01-06 20:12:53

+0

該代碼最初是爲了匹配類別AND標籤而編寫的,我重新閱讀了該問題並更改了代碼,以便與類別OR標籤匹配 – 2010-01-06 20:43:06

+0

您現在正在對字符串調用intersect()方法? – Langali 2010-01-06 20:47:52

-1

理想的查詢時,你會使用條件查詢,錯誤既然你說你不關心性能,東西像這應該工作:

def category = 
def tagName 

def relatedArticles = Article.list().findAll { 
    (it.categoryName == myArticle.categoryName) || (it.tags.contains(tagName))    
} 
+0

一篇文章有​​多個標籤。那麼如何包含多個標籤的工作呢? – Langali 2010-01-06 20:30:27

+0

另外,我對使用標準的解決方案感興趣。要試試嗎? – Langali 2010-01-06 20:31:51

+0

您的問題,正如所述的要求「通過CategoryName或Tag Name查找所有文章」。 – 2010-01-07 01:19:49

0

我認爲你需要使用每篇文章標籤一個單獨的查詢:

// Use a LinkedHashSet to retain the result order if that is important 
def results = new LinkedHashSet() 

results.addAll(Article.findAll("from Article as article \ 
    where article.categoryName = :categoryName \ 
    and article.id != :id", 
    [ 
    categoryName:myArticle.categoryName, 
    id:myArticle.id, 
    ]) 

myArticle.tags.each { 
results.addAll(Article.executeQuery(
    "select distinct article from Article as article, \ 
    Tag as tag \ 
    where tag.name = :tag \ 
    and tag in elements(article.tags) \ 
    and article.id != :id", 
    [ 
    tag:it.name, 
    id:myArticle.id, 
    ])) 
} 

def relatedArticles = results as List 

這當你在系統中有很多內容並且希望避免爲單個頁面請求加載整個數據庫時顯然是值得的。其他改進包括爲查詢指定最大和偏移量參數。