mirror of
https://github.com/serty2005/rmser.git
synced 2026-02-04 19:02:33 -06:00
39 lines
825 B
Go
39 lines
825 B
Go
package recipes
|
|
|
|
import (
|
|
"rmser/internal/domain/recipes"
|
|
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
)
|
|
|
|
type pgRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewRepository(db *gorm.DB) recipes.Repository {
|
|
return &pgRepository{db: db}
|
|
}
|
|
|
|
func (r *pgRepository) SaveRecipes(list []recipes.Recipe) error {
|
|
return r.db.Transaction(func(tx *gorm.DB) error {
|
|
for _, recipe := range list {
|
|
if err := tx.Omit("Items").Clauses(clause.OnConflict{
|
|
Columns: []clause.Column{{Name: "id"}},
|
|
UpdateAll: true,
|
|
}).Create(&recipe).Error; err != nil {
|
|
return err
|
|
}
|
|
if err := tx.Where("recipe_id = ?", recipe.ID).Delete(&recipes.RecipeItem{}).Error; err != nil {
|
|
return err
|
|
}
|
|
if len(recipe.Items) > 0 {
|
|
if err := tx.Create(&recipe.Items).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
}
|