i have a many to many relation like a customers and orders.
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}
when i preload ShiftMaps using
db.Preload("ShiftMaps").Find(&employeeShiftList) same shift of an employee is populated more than once inside ShiftMaps struct of the customer. how can i avoid this.
2
Answers
Since my join table had additional fields FromDate and ToDate it was difficult to populate them using many to many table structure. so i simplified my structure. i created a table employee_shifts. employees
One possible solution is to use the distinct option in GORM’s Preload to ensure that only distinct values are loaded. Here’s how you can modify your query: