go_service/gorm_models/brand.go

50 lines
1.1 KiB
Go
Raw Permalink Normal View History

2022-08-12 08:59:03 +00:00
package gorm_models
import (
"log"
"time"
"github.com/gosimple/slug"
"gorm.io/gorm"
)
type Brand struct {
ID uint `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
2022-08-25 05:39:59 +00:00
Name string `gorm:"default:TESTBRAND"`
2022-08-12 08:59:03 +00:00
Code string
Status bool
2022-09-25 17:24:33 +00:00
Categories []Category `gorm:"many2many:category_brands;"`
2022-08-12 08:59:03 +00:00
}
2022-09-25 17:24:33 +00:00
func FindOrCreateBrand(db *gorm.DB, brand string, categories []Category) (Brand, error) {
2022-08-12 08:59:03 +00:00
var brandObject Brand
if brand != "" {
code := slug.Make(brand)
2022-12-21 09:02:58 +00:00
err := db.FirstOrCreate(&brandObject, Brand{Name: brand, Code: code}).Error
2022-12-21 08:47:50 +00:00
//err := db.Model(Brand{Name: brand, Code: code}).First(&brandObject).Error
//log.Println(Brand{Name: brand, Code: code})
2022-08-12 08:59:03 +00:00
if err != nil {
2022-12-21 08:47:50 +00:00
//err := db.Omit("Categories.*").FirstOrCreate(&brandObject, Brand{Name: brand, Code: code, Categories: categories}).Error
2022-09-22 12:31:59 +00:00
log.Println("ERR0000000000000001" + err.Error())
2022-09-22 15:10:51 +00:00
return brandObject, err
2022-08-12 08:59:03 +00:00
}
2022-12-21 09:02:58 +00:00
db.Model(&brandObject).Association("Categories").Append(categories)
2022-12-21 08:01:48 +00:00
return brandObject, nil
2022-08-12 08:59:03 +00:00
}
// var brandObject Brand
2022-09-22 15:10:51 +00:00
return brandObject, nil
2022-08-12 08:59:03 +00:00
}