base.go 562 B

12345678910111213141516171819202122232425262728
  1. package models
  2. import (
  3. "errors"
  4. "github.com/astaxie/beego/orm"
  5. )
  6. // 唯一索引字段close实体
  7. type UniqueClone[T any] interface {
  8. UniqueClone() (*T, string)
  9. }
  10. func InsertOrUpdate[T any](o orm.Ormer, md UniqueClone[T], cols ...string) (int64, error) {
  11. if o == nil {
  12. o = orm.NewOrm()
  13. }
  14. exist, key := md.UniqueClone()
  15. if cols == nil || len(cols) == 0 {
  16. cols = []string{key}
  17. }
  18. err := o.Read(exist, cols...)
  19. if err != nil && errors.Is(err, orm.ErrNoRows) {
  20. return o.Insert(md)
  21. } else if err != nil {
  22. return 0, err
  23. }
  24. return o.Update(md)
  25. }