【问题标题】:GORM Query on Multiple Parent and Child Objects With Parent's Property具有父属性的多个父子对象的 GORM 查询
【发布时间】:2013-07-02 15:18:56
【问题描述】:

仅供参考,请随时为此建议一个更好的标题。我有以下领域模型(我们无法控制):

class Foo {
    int id
    String baz
    Date someDate
    static hasMany = [bars:Bar]
    static mapping = {
        id composite: [ "id", "baz" ]
    }
}

class Bar {
    int id
    String baz
    Date someDate
    Foo foo
    static mapping = {
        id composite: ["id", "baz", "someDate"]
        columns {
            foo([:]) {
                column name: "id"
                column name: "baz"
            }
        }
    }
}

我的问题是:我有一个 Foo 列表,我需要找到 Foo.someDate == Bar.someDate 的所有 Bars,但仅在一个查询中而不是对每个 Foo 的查询中,不涉及延迟加载。也不能将 Bars 设置为渴望获取。

例如,如果这是我的数据(伪代码,为了简单起见,我将 id 和 baz 组合成简单的“id”):

[
    Foo (someDate:4/1/2013)
        |___ bars: [{someDate:12/4/2012, id:1}, {someDate:4/1/2013, id:2}]
    Foo (someDate:5/10/2012)
        |___ bars: [{someDate:{4/1/2013, id:3}
    Foo (someDate:3/3/2013)
        |___ bars: [{someDate:3/3/2013, id:4}, {someDate:9/5/2013, id:5}]
]

我需要在一个查询中返回 id 为 2 和 4 的 Bars。我真的不知道如何处理这个问题。

如有必要,它可以是 HQL,但最好是 GORM 查询。

【问题讨论】:

    标签: grails grails-orm parent-child subset


    【解决方案1】:

    试试这个:

    Bar.executeQuery("select b from Bar b join b.foo as f where b.someDate = f.someDate and f in :fooList", [fooList: fooList])
    

    【讨论】:

    • 不是 GORM,但它很简单,完全符合我的需要。
    【解决方案2】:

    不确定这是否是最好的方法,但我认为它会给你结果

    :)

    Bar.executeQuery("select b.id from Bar b, Foo f where b.someDate = f.someDate")
    

    虽然我已经删除了您的复合映射约束然后尝试了它,但对我有用:)

    或使用 where 查询:

    def km = Bar.where {
                foo.someDate==someDate
    
            }
    println(km.list())
    

    如果你已经有 foo 列表,那么可以通过 findAll 闭包过滤:

    fooList.findAll{it.someDate in it.bars.someDate} 
    

    :)

    【讨论】:

    • 这将查询所有 Foos 对吗?我只希望它查询我当前拥有的列表。
    • 是的,我认为它会查询所有 foo :)
    • 好吧...不是我想要的。是否可以将其修改为仅使用现有的 Foos 列表进行查询?
    • 所以基本上你有一些 foos 列表并且想要对其运行查询?
    • 同样可以通过 where 查询完成,但我认为您不想要它,但我已将其添加到答案中,它可能对其他人有帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多