首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >grails标准投影的Mysql group_concat替代方案

问grails标准投影的Mysql group_concat替代方案
EN

Stack Overflow用户
提问于 2013-06-26 21:39:32
回答 2查看 780关注 0票数 1

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

代码语言:javascript
复制
class A {
    String name

    static hasMany = [bs: B]
}

class B {
    String title
}

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

代码语言:javascript
复制
// 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"
...

这是我达到这个目标的标准:

代码语言:javascript
复制
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元素的第一个标题。如下所示:

代码语言:javascript
复制
1, "A1", "B1"
2, "A2", "B2"
...

现在,现实生活中的场景有点复杂,我已经简化到了要点,那就是:我如何才能在bs标题上获得与mysql group_concat相同的效果?

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

EN

回答 2

Stack Overflow用户

发布于 2013-06-27 00:53:41

它与您的具有排序的实现相同。

代码语言:javascript
复制
    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获得每个组合的键值对。

代码语言:javascript
复制
//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]]
]
票数 0
EN

Stack Overflow用户

发布于 2013-06-27 09:59:43

这是另一种方法

代码语言:javascript
复制
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()}"
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17321670

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档