官網的文檔:https://gorm.io/zh_CN/docs/associations.html
需求:角色和資源,兩個表數據單獨維護,然後做數據關聯。二者是多對多的關係,兩個主鍵均爲ID(string類型,值爲uuid)。
如果按照官方文檔做,代碼如下:
db.Model(&role).Association("Resources").Append(resList) // resList爲資源列表
執行結果會是,相同數據的resource被複制一遍添加到resource表中,並在role_resources表中添加關聯關係。
與最初設想只是添加關聯關係記錄剛好相反。
又嘗試了先清空再添加的邏輯:
db.Model(&role).Association("Resources").Clear()
db.Model(&role).Association("Resources").Append(resList)
效果還是複製了一遍資源數據,再添加關聯關係。
怎麼辦?
最後,只能手動建立關聯關係結構
type RoleResources struct {
RoleID string `gorm:"primaryKey"`
ResourceID string `gorm:"primaryKey"`
}
然後在代碼中手動維護二者的關聯關係。