使用具有多对多关系的

使用具有多对多关系的

本文介绍了使用具有多对多关系的 Grails 的 withCriteria 函数的重复问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个表,问题和答案,具有多对多关系(即问题可以有多个答案,而答案可以被多个问题重复使用).为了规范化,我在它们之间有一个名为 Question_Answer 的交叉引用表,它与两个表都具有多对一的关系.这些是它们的类定义:

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
}

我正在尝试根据特定条件获取答案列表.这是我的标准查询(使用 Grails 的 withCriteria 函数):

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:

我有一个与 3 个不同问题相匹配的答案.我在列表"中想要的是 1 个 Answer 对象,其 questionAnswers 列表填充了 3 个匹配的 QuestionAnswer 对象.相反,我得到了 3 个相同的 Answer 对象,所有对象都填充了它们的 questionAnswers 列表.

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.

谢谢,B.J.

推荐答案

尝试将其添加到您的查询中以告诉 Criteria 仅返回不同的 Answer 对象:

Try adding this to your query to tell the Criteria to return only distinct Answer objects:

resultTransformer org.hibernate.Criteria.DISTINCT_ROOT_ENTITY

这篇关于使用具有多对多关系的 Grails 的 withCriteria 函数的重复问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 01:13