tags:

views:

68

answers:

2
Article { 
   String categoryName 
   static hasMany = [ 
        tags: Tag 
    ] 
} 

Tag { 
   String name 
}

Now I want to find the list of all related articles. Related meaning, all articles that have the same category name as myArticle or any of the same tags as myArtcle.

With only matching categoryName, here is how I would get the relatedArticles using closures.

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

Anyone wants to give a shot to find all articles by CategoryName or Tag Name (in a groovy way)?

Any solutions using Criteria or custom queries is appreciated too.

+1  A: 

This would work:

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

However, if you have a reasonably large number of articles and only a small number of them are expected to match it would be horribly inefficient, as this will load all articles then iterate through them all looking for matches.

A better way would be to simply write a query that only loads matching articles (instead of calling Article.list())

Don
Agreed on the performance issues. I only have about a 50 articles and it isn't going to increase by much.
Langali
The code was originally written to match category AND tags, I re-read the question and changed the code so it matches category OR tags
Don
You are now calling the intersect() method on a String?
Langali
My bad, sorry!!!!
Langali
`article.tags.name` will create a list that contains the name of every tag used in the article
Don
Why are you calling Article.list().findAll rather than using the short hand Article.findAll?
Einar
A: 

Ideally, you'd use Criteria Query, bug since you said you are not concerned about performance, something like this should work:

def category = 
def tagName

def relatedArticles = Article.list().findAll {
    (it.categoryName == myArticle.categoryName) || ( it.tags.contains(tagName) )            
} 
Jean Barmash
An article has more than one tags. So how would that contains work for multiple tags?
Langali
Also, I am interested in your solution using criteria. Wanna try?
Langali
Your question, as stated asked for "find all articles by CategoryName or Tag Name."
Jean Barmash