dongranding3909 2019-01-31 08:45
浏览 24

如何为实体A设置结构标记可能在GORM中包含B并使make自动创建和预加载

Consider I have BaseNotification and ExtendedNotification structs.

For some notifications they use base_notificaion table only yet some of them will save some extra data into extended_notificaion.

How to setup struct tag in these two structs so that when I run

db.Create(&entendedNotification) // or something else

GORM will know it need to insert a new tuple into extended_notification if needed(for example either it is not nil or fields are filled)

And when I call

db.Preload(`ExtendedNotification`).Find(&notifications)

it will grab all necessary entities accordingly?

  • 写回答

1条回答 默认 最新

  • douyan4958 2019-01-31 09:02
    关注

    If you ensure A's primary key id is a foreign key in B, use like this

    type A struct{
        Id int `gorm:"column:id"`
        B []B `gorm:"column:b;ForeignKey:Aid"`
    }
    type B struct{
        Aid int 
    }
    

    if not, I suggest using

    func (a *A) AfterFind()error{
        return db.Model(&B{}).Find(&a.B).Error
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程