我有多对多的关系,比如客户和订单。
type EmployeeShiftList struct {
ID uint
UUID uuid.UUID `gorm:"<-:create"`
FirstName string `validate:"required,max=250"`
LastName string `validate:"omitempty,max=250"`
ShiftMaps []ShiftMap `gorm:"many2many:attendance.employee_shifts;foreignKey:ID;References:ShiftID;joinForeignKey:EmployeeID;joinReferences:ShiftID"}
type ShiftMap struct {
ShiftID uint `gorm:"primaryKey"`
FromDate time.Time
ToDate time.Time}
当我使用预加载 ShiftMaps 时 db.Preload("ShiftMaps").Find(&employeeShiftList) 员工的同一班次在客户的 ShiftMaps 结构中多次填充。我怎样才能避免这种情况。
一种可能的解决方案是使用 GORM 的 Preload 中的 unique 选项来确保仅加载不同的值。以下是修改查询的方法:
db.Preload("ShiftMaps", func(db *gorm.DB) *gorm.DB {
return db.Distinct("shift_maps.shift_id") // Assuming ShiftID is the unique identifier in ShiftMap
}).Find(&employeeShiftList)