Search code examples
grailsgrails-orm

Grails get list of A's where searching with B's in many to many relationship


I have the following domain objects:

class Blog {
   String foo
}

class Comment {
   String bar
}

class BlogComment {
   Blog blog
   Comment comment
}

So far I've written this:

def getComments(Blog blog) {
    def blogCommentCriteria = BlogComment.createCriteria()

    def blogCommentResults = blogCommentCriteria.list {
        eq 'blog.id', blog.id
    }

    List<Comment> comments = new Vector<Blog>()

    blogCommentResults.each { i ->
        if(i.blog == blog) {
            comments.add(i.comment)
        }
    }

    comments
}

What would be the most efficient method? I want the method to be clean and simple, but also efficient in terms of time taken.


Solution

  • You can add a method to the Blog class to get the comments associated with a given blog:

    class Blog {
       String foo
    
       def getComments() {
            BlogComment.findAllByBlog(this)*.comment
       }
    }