mirror of
https://github.com/serty2005/rmser.git
synced 2026-02-05 03:12:34 -06:00
start rmser
This commit is contained in:
38
internal/infrastructure/repository/recipes/postgres.go
Normal file
38
internal/infrastructure/repository/recipes/postgres.go
Normal file
@@ -0,0 +1,38 @@
|
||||
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
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user