I’ve got 2 tables, Question and Answer, with a many-to-many relationship (i.e. Questions can have multiple Answers and Answers can be reused by multiple Questions). For normalization, I have a cross-reference table between them named Question_Answer that has a many-to-one relationship with both tables. These are their class definitions:
class Question {
int id
int text
static hasMany = [questionAnswers : QuestionAnswer]
}
class Answer {
int id
int text
static hasMany = [questionAnswers : QuestionAnswer]
}
class QuestionAnswer {
int id
Question question
Answer answer
}
I’m trying to get a list of Answers based on certain criteria. Here is my criteria query (using Grails’ withCriteria function):
def listing = Answer.withCriteria {
cache false
order "id", "asc"
eq("id", myAnswerID)
questionAnswers {
question {
isNotNull("text")
}
}
}
Here’s an example of the problem I’m having:
I have an Answer that matches 3 different Questions. What I want in the “listing” is 1 Answer object, with its questionAnswers list populated with the 3 matching QuestionAnswer objects. Instead, I’m getting 3 identical Answer objects, all with their questionAnswers lists populated.
Is there a simple way to achieve what I want? I’m hoping I’m just missing something small.
Any help/suggestions are much appreciated.
Thanks,
B.J.
Try adding this to your query to tell the Criteria to return only distinct Answer objects: