Note that there are some explanatory texts on larger screens.

plurals
  1. POProblem with duplicates using Grails' withCriteria function with a many-to-many relationship
    text
    copied!<p>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:</p> <pre><code>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 } </code></pre> <p>I'm trying to get a list of Answers based on certain criteria. Here is my criteria query (using Grails' <code>withCriteria</code> function):</p> <pre><code>def listing = Answer.withCriteria { cache false order "id", "asc" eq("id", myAnswerID) questionAnswers { question { isNotNull("text") } } } </code></pre> <p>Here's an example of the problem I'm having:</p> <p>I have an Answer that matches 3 different Questions. What I want in the "listing" is 1 <code>Answer</code> object, with its <code>questionAnswers</code> list populated with the 3 matching <code>QuestionAnswer</code> objects. Instead, I'm getting 3 identical <code>Answer</code> objects, all with their <code>questionAnswers</code> lists populated.</p> <p>Is there a simple way to achieve what I want? I'm hoping I'm just missing something small.</p> <p>Any help/suggestions are much appreciated.</p> <p>Thanks, B.J.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload