Gorm使用笔记

517 阅读1分钟

#1 关联模式批量更新

模型信息如下,现在要解决的是批量插入或更新[]MtHotelBaseInfo如何也一并批量插入或更新MtHotelExtInfoMtHotelImages

// 酒店基础信息
type MtHotelBaseInfo struct {
    gorm.Model
    HotelId         int             `json:"hotelId" gorm:"column:hotel_id;uniqueIndex;comment:酒店ID"`
    PointName       string          `json:"pointName" gorm:"column:hotel_name;size:80;comment:酒店中文"`
    PointNameEn     string          `json:"pointNameEn" gorm:"column:hotel_name_en;size:100;comment:酒店英文"`
    Longitude       int             `json:"longitude" gorm:"column:lon;comment:实际经度值*10的6次方取整"`
    Latitude        int             `json:"latitude" gorm:"column:lat;comment:实际纬度值*10的6次方取整"`
    ExtInfo         MtHotelExtInfo  `json:"poiExtInfo" gorm:"foreignKey:HotelId;references:hotel_id;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
    ImageList       []MtHotelImages `json:"poiImages" gorm:"foreignKey:HotelId;references:hotel_id;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
}

// 酒店附属信息
type MtHotelExtInfo struct {
    gorm.Model
    HotelId          int    `json:"hotelId" gorm:"column:hotel_id;uniqueIndex;comment:酒店ID"`
    OpenDate         string `json:"openDate" gorm:"column:open_date;size:20;comment:开业时间"`
    DecorationDate   string `json:"decorationDate" gorm:"column:decoration_date;size:20;comment:装修时间"`
    StarRating       int    `json:"starRating" gorm:"column:star;type:tinyint;comment:星级0 5星 1 4.5星->10 0星"`
}

// 酒店图片信息
type MtHotelImages struct {
    gorm.Model
    HotelId  int    `json:"-" gorm:"column:hotel_id;uniqueIndex:IX_hotel_id_url;comment:酒店ID"`
    TypeId   int    `json:"typeId" gorm:"column:type_id;type:tinyint;comment:图片类型, 1:环境,9: 10其他,19:公共设施,32:大厅,34:外观,40:客厅,外观,41:厨房,42:卫浴,49:餐饮,50:休闲娱乐"`
    TypeName string `json:"typeName" gorm:"column:type_name;size:50;comment:图片类型名称"`
    Url      string `json:"url" gorm:"column:url;uniqueIndex:IX_hotel_id_url;comment:图片URL地址"`
}
  • 1 使用FullSaveAssociations模式进行更新:缺点是MtHotelExtInfoMtHotelImagescreated_at也会一起更新
// HotelBaseInfoList 是 []MtHotelBaseInfo
err := db.Clauses(clause.OnConflict{
     UpdateAll: true,
}).Session(&gorm.Session{FullSaveAssociations: true}).Create(&HotelBaseInfoList).Error
// todo
  • 2 使用hook,完美解决
// HotelBaseInfoList 是 []MtHotelBaseInfo
err := db.Create(&h.HotelBaseInfoList)
// todo
func (h *MtHotelBaseInfo) BeforeSave(tx *gorm.DB) error {
	tx.Statement.AddClause(clause.OnConflict{
		UpdateAll: true,
	})
	return nil
}

func (e *MtHotelExtInfo) BeforeSave(tx *gorm.DB) error {
	tx.Statement.AddClause(clause.OnConflict{
		UpdateAll: true,
	})
	return nil
}

func (i *MtHotelImages) BeforeSave(tx *gorm.DB) error {
	tx.Statement.AddClause(clause.OnConflict{
		UpdateAll: true,
	})
	return nil
}