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
    }
    
    评论

报告相同问题?