Grails Many to Many Association Querying
-
20-09-2019 - |
Question
I have a many to many relationship.
class Post {
String title
static hasMany = [tags:Tag]
}
class Tag {
static hasMany = [posts:Post]
}
I would like to get a list of posts for a tag that have some other criteria (like a sort order, partial title match, etc). Do I have to use the grails criteria to achieve this? Or is there some way to do something like this:
Post.findAllByTitleLikeAndTagsContains("partial title", aTag)
Solution
I don't think dynamic finders will allow you to get into one to many or many to many associations - you have to do a criteria or go the HQL query route. You can only query by one to one association, not by one to many. (see section 5.4.1 Dynamic Finders)
OTHER TIPS
You can use withCriteria,for example:
Post.withCriteria{
tags {
eq 'id',aTag.id
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow