假设我有以下域:
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']
}
换句话说,在
Store
和Product
之间存在多对多关系,中间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/