我有以下定义的gorm实体

type Location struct {
    gorm.Model
    RoomNo     string `gorm:"unique_index:roomno_level_buildingid"`
    Level      string `gorm:"unique_index:roomno_level_buildingid"`
    BuildingID string `gorm:"unique_index:roomno_level_buildingid"`
}
type Sensors struct {
    gorm.Model
    Location   Location
    LocationID uint
    Type string
}

三元组(RoomNo,Level,BuildingID)应该是唯一的 . 根据我的理解,这将是一种“有一种”关系 .

当我插入具有相同“位置”三元组的新传感器元组时,如何避免约束违规?到目前为止,我的方法是查询现有“Locations”三元组的数据库(它是postgresql),并在“Sensors”实例中设置(!)相应的字段,调用gorm.DB.Save(...) .