grails - 在Grails中,如何在 View 和 Controller 中使用中间连接类处理多对多?

标签 grails

假设我有以下域:

class Store {
    String name

    static hasMany = [ products: StoreProduct ]
}

class Product {
    String name

    static hasMany = [ stores: StoreProduct ]
}

class StoreProduct {
    BigDecimal discount

    static belongsTo = [ store: Store, product: Product ]
    static mapping = {
        id composite: ['store', 'product']
    }

换句话说,在StoreProduct之间存在多对多关系,中间StoreProduct域类用于跟踪每个商店的个人折扣。

Grails对一对多关系具有内置支持,因此您可以传入具有正确字段名称的ID列表, Controller 将自动将ID解析为实体列表。但是,在这种情况下,它是一个多对多的中间域类。

我已经在Store编辑 View 中尝试了以下代码,以允许用户选择产品列表:
<g:each in="${products}" var="product" status="i">
    <label class="checkbox">
        <input type="checkbox" name="products" value="${product.id}"/>
         ${product.name}
    </label>
</g:each>

但是Grails会引发各种错误,具体取决于我对name属性使用的内容。我还尝试了以下input名称:
products
products.product
products.product.id
product[0].product
product[0].product.id

但是它们都不能正常工作。

我的问题是,Grails中是否存在对这种关系的内置支持,尤其是在 View 方面?

最佳答案

更改您的域结构,如下所示:

class Store {
    String name

    Set<Product> getProducts() {
       StoreProduct.findAllByStore(this)*.product
    }
}

class Product {
    String name
    Set<Store> getStores() {
        StoreProduct.findAllByProduct(this)*.store
    }
}

import org.apache.commons.lang.builder.HashCodeBuilder
class StoreProduct implements Serializable {

    BigDecimal discount
    Store store
    Product product

    static mapping = {
        id composite: ['store', 'product']
        version false
    }

boolean equals(other) {
    if (!(other instanceof StoreProduct)) {
        return false
    }

    other.store?.id == store?.id &&
        other.product?.id == product?.id
}

int hashCode() {
    def builder = new HashCodeBuilder()
    if (store) builder.append(store.id)
    if (product) builder.append(product.id)
    builder.toHashCode()
}
}

关于grails - 在Grails中,如何在 View 和 Controller 中使用中间连接类处理多对多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16027436/

相关文章:

python - 如何从 Grails 调用 Python 库(提到 Jython)?

unit-testing - 在 grails 中,如何测试具有关联的 where 查询?

grails - 如何在 BIRT 报告中使用 Grails 并显示 BIRT Web 查看器

grails - 如何在Grails项目文档中提供指向文件的链接

multithreading - GORM实例对象线程安全

html - 可以在 <g :actionSubmit> tag? 中添加 css

grails - 如果指定任何上下文,则grails 2.5 dbm-update总是会因MissingMethodException失败

http - 从grails中的POST请求中读取Word文件

validation - Grails 命令对象自定义验证消息代码

tomcat - 是否可以将根域 URL 映射到 Grails 的 Controller ?