Refactor AssignLabelsToChore function to optimize label assignment and avoid unnecessary

This commit is contained in:
Mo Tarbin 2024-11-27 19:14:16 -05:00
parent d3792f8e7b
commit a0265de264

View file

@ -73,16 +73,18 @@ func (r *LabelRepository) AssignLabelsToChore(ctx context.Context, choreID int,
}) })
} }
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if len(toBeRemoved) > 0 {
if err := r.db.WithContext(ctx).Where("chore_id = ? AND user_id = ? AND label_id IN (?)", choreID, userID, toBeRemoved).Delete(&chModel.ChoreLabels{}).Error; err != nil { if err := r.db.WithContext(ctx).Where("chore_id = ? AND user_id = ? AND label_id IN (?)", choreID, userID, toBeRemoved).Delete(&chModel.ChoreLabels{}).Error; err != nil {
return err return err
}
} }
if len(toBeAdded) > 0 {
if err := r.db.WithContext(ctx).Clauses(clause.OnConflict{ if err := r.db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "chore_id"}, {Name: "label_id"}, {Name: "user_id"}}, Columns: []clause.Column{{Name: "chore_id"}, {Name: "label_id"}, {Name: "user_id"}},
DoNothing: true, DoNothing: true,
}).Create(&choreLabels).Error; err != nil { }).Create(&choreLabels).Error; err != nil {
return err return err
}
} }
return nil return nil
}) })