grails - 有没有办法用 mongodb 控制 gorm 中的加载关系?

标签 grails grails-orm grails-3.0 gorm-mongodb

我正在用 grails 3 和 mongo 构建一个 REST api。当我需要编码具有更大深度的对象图时,我遇到了一个问题。

我有以下域:

class Category extends Resource {
    /* other fields */

    Category parent
}

class Product extends Resource {
    /* other fields */

    List<Category> categories
    static hasMany = [categories: Category]
}

我在数据库中有以下结构(为便于理解而简化):
categories:
{name: 'cat1'}
{name: 'cat2', parent: 'cat3'}
{name: 'cat3', parent: 'cat4'}
{name: 'cat4', parent: 'cat5'}
{name: 'cat5'}

product: 
{categories: ['cat1', 'cat2']}

创建 Controller 时,我从 RestfullController 扩展。我希望能够获得产品并在返回的 json 中包含 parent 的类别。

我得到以下结果:
/product/${id} 
{
    id: '...',
    categories: [{
        id: '...',
        name: 'cat1'
    }, {
        id: '...',
        name: 'cat2',
        parent: { id: '...' }
    }]
} 

/category/cat2id 
{
    id: '...',
    name: 'cat2',
    parent: { id: '...' }
}

/category
[{
    id: '...',
    name: 'cat1'
},{
    id: '...',
    name: 'cat5'
},{
    id: '...',
    name: 'cat4',
    parent: {
        id: '...',
        name: 'cat5'
    }
},{
    id: '...',
    name: 'cat3',
    parent: {
        id: '...',
        name: 'cat4',
        parent: {
            id: '...',
            name: 'cat5'
        }
    }
},{
    id: '...',
    name: 'cat2',
    parent: {
        id: '...',
        name: 'cat3',
        parent: {
            id: '...',
            name: 'cat4',
            parent: {
                id: '...',
                name: 'cat5'
            }
        }
    }
}]

为什么 Category.list() 会加载整个类别对象图,而 Category.get()、Product.get() 和 Product.list() 不会加载它?有没有办法控制这种行为?

最佳答案

Grails 的工作方式是它只会渲染已经从数据库加载的关联,因此为什么会渲染一些关联而其他关联不会。

除了编写自己的编码器之外,没有内置的方法可以控制这种行为。见 http://grails.github.io/grails-doc/latest/guide/webServices.html#renderers

关于grails - 有没有办法用 mongodb 控制 gorm 中的加载关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33830477/

相关文章:

hibernate - GORM IdentityEnumType 与 Grails 2.5.6 映射 NPE

Grails GORM : list all with nested property

grails - 如何将 mongodb 和/或 postgresql-extension 插件添加到 Grails 3.0.0+ 中?

jakarta-ee - 在 grails 中创建耳朵

unit-testing - 如何在 Grails 单元测试中使用 Spock 模拟 passwordEncoder

Grails 逆向工程师数据库

grails - 结合@TestFor和@Integration注释grails 3

validation - grails 整数字段默认验证

grails 命令在终端中不起作用

maven - 将 grails3 插件发布到 Artifact - 生成的 pom 的差异