1

假设我有两个简单的域类:

class A {
    String name

    static hasMany = [bs: B]
}

class B {
    String title
}

现在,我想生成一个结构如下的项目列表:

// id of A instance, name of A instance, comma separated list of Bs titles associated to A istance
1, "A1", "B1, B2"
2, "A2", "B2, B5"
...

这是我的标准:

def list = A.withCriteria {
    createAlias 'bs', 'bs', CriteriaSpecification.LEFT_JOIN

    projections {
        property 'id'
        property 'name'

        property 'bs.title' // this is the interesting line
    }
}

这显然只检索与​​我的 A 实例相关的 B 元素的第一个标题。像这样:

1, "A1", "B1"
2, "A2", "B2"
...

现在,现实生活中的场景有点复杂,我已经简化了重点,那就是:我怎样才能得到 mysql group_concat 对 bs 标题的相同效果?

我试图在一个单一的标准中做到这一点,但如果不可能,我很乐意讨论不同的解决方案。

4

2 回答 2

0

这是另一种方式

class A {
    String name
    static hasMany = [bs: B]

    def childrenString() {
        B.findAllByParent(this).collect{ it.title }.join(',')
    }
}

class B {
    static belongsTo = A
    A parent
    String title
    static constraints = {
    }
}

A.list().each  { it ->
    println "${it.name}, ${it.childrenString()}"
}
于 2013-06-27T01:59:43.320 回答
0

它与您的排序实现相同。

    def list = A.withCriteria {
        createAlias 'bs', 'bs', CriteriaSpecification.LEFT_JOIN
        projections {
            property 'id'
            property 'name'
            property 'bs.title' // this is the interesting line
        }

        order "id", "asc"
        order "bs.title", "asc"
    }


    //Bootstrap
    def a = new A(name: "TestA1").save()
    def a1 = new A(name: "TestA2").save()

    def b1 = new B(title: "TitleB1")
    def b2 = new B(title: "TitleB2")
    def b3 = new B(title: "TitleB3")

    def b4 = new B(title: "TitleB4")
    def b5 = new B(title: "TitleB5")

    [b1, b2, b3].each{a.addToBs(it)}
    [b2, b4, b5].each{a1.addToBs(it)}

    [a, a1]*.save(flush: true, failOnError: true)

您可以通过 groupBy 来获取每个组合的键值对。

//This can be optimized
list.groupBy({[it[0], it[1]]})

//Would give
[[1, TestA1]:[[1, TestA1, TitleB1], [1, TestA1, TitleB2], [1, TestA1, TitleB3]], 
 [2, TestA2]:[[2, TestA2, TitleB2], [2, TestA2, TitleB4], [2, TestA2, TitleB5]]
]
于 2013-06-26T16:53:40.840 回答