【问题标题】:How to preload in gorm many to many with the condition in join table如何使用连接表中的条件在gorm中预加载多对多
【发布时间】:2021-08-08 18:32:16
【问题描述】:

又是我…… 现在对我来说是个大问题,但我很难考虑 现在我可以在gorm中预加载。但是当使用连接表对多对多表使用预加载时......我有一些我不知道的问题 我有 3 张桌子

type Product struct{
Categories []Category `gorm:"many2many:Product_Category"`
}
type Category struct{}
type Product_Category struct {}

类似的。我现在可以使用 Preload("Categories").Find(&products) 但这里的问题是如何过滤产品类别? 意思是我需要在预加载类别时在联接表 Product_Category 中添加条件?有什么解决办法吗?

除此之外,我想知道如何将带有类别的产品添加/更新到 2 表 Product 和 Product_Category 中?

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:
    type Product struct{
    Product
    Categories []Category `gorm:"many2many:product_category;foreignKey:ID;joinForeignKey:ProductID;References:ID;joinReferences:CategoryID"`
    }
    type Category struct{}
    type Product_Category struct {}
    

    这是说

    • 创建多 2 多关系,其中 1 个外键是一个模型的 ID,参考为“product_id”,其他模型类似。
    • 那么您只需预加载类别

    【讨论】:

    • 嘿。谢谢你的帮助。但我几乎解决了这个问题!祝你有美好的一天
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多