Mysql group_concat替代grails标准投影

时间:2013-06-26 13:39:32

标签: hibernate grails criteria group-concat

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

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"
...

现在,现实生活中的场景有点复杂,我已经简化到了这一点,即:我怎样才能获得与bs游戏相同的mysql group_concat效果?

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

2 个答案:

答案 0 :(得分: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]]
]

答案 1 :(得分: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()}"
}