gpt4 book ai didi

grails - 如何在联接表包含标识类型的情况下表示多对多关系

转载 作者:行者123 更新时间:2023-12-02 15:42:15 25 4
gpt4 key购买 nike

在运行Grails 3.3.10的过程中,我有一个Product实体,该实体与Message表在2个单独的字段(product.type1Messages和product.type2Messages)上具有多对多关系,并且“type”字段位于以下位置的联接表中数据库。

是否可以使用映射将正确的消息放入正确的集合中?

请在下面找到我的代码:

CREATE TABLE `productmessage` (
`productId` int(11) NOT NULL,
`messageId` int(11) NOT NULL,
`type` int(11) NOT NULL,
PRIMARY KEY (`productId`,`messageId`,`type`)
);

class Product {

static hasMany = [ type1Messages: Message, type2Messages: Message ]

static mappedBy = [ type1Messages: "type1Product", type2Messages: "type2Product" ]

static mapping = {
type1Messages joinTable: [name: 'productmessage', key: 'productId', column: 'messageId']
type2Messages joinTable: [name: 'productmessage', key: 'productId', column: 'messageId']
}
}

class Message {

Product type1Product
Product type2Product

static mapping = {
type1Product column: "productId"
type2Product column: "productId"
}
}

我需要 product.type1Messages在连接表中仅包含类型1的那些,而 product.type2Messages包含类型2的那些。这可能吗?如果可以,我需要添加什么?

编辑
我只是意识到我可能会通过陈述多对多关系,然后将示例简化为仅显示一对多来使事情感到困惑。请注意,我的问题是联接表中的类型,而不是如何表示多对多。

最佳答案

我会为此使用一些特殊的类。像这样:

abstract class ProductMessage {
Product product
Message message
}

class Type1ProductMessage extends ProductMessage {

}

class Type2ProductMessage extends ProductMessage {

}
class Product {

static hasMany = [ type1Messages: Type1ProductMessage, type2Messages: Type2ProductMessage ]
}

如果您不想使用抽象类,则可以将第一个作为主要类,并从第一个开始扩展第二个。

在数据库中,它将映射为:
'id'
'product_id'
'message_id'
'class'

关于grails - 如何在联接表包含标识类型的情况下表示多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56275888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com