12345678910111213141516171819202122232425262728 |
- package models
- import (
- "errors"
- "github.com/astaxie/beego/orm"
- )
- // 唯一索引字段close实体
- type UniqueClone[T any] interface {
- UniqueClone() (*T, string)
- }
- func InsertOrUpdate[T any](o orm.Ormer, md UniqueClone[T], cols ...string) (int64, error) {
- if o == nil {
- o = orm.NewOrm()
- }
- exist, key := md.UniqueClone()
- if cols == nil || len(cols) == 0 {
- cols = []string{key}
- }
- err := o.Read(exist, cols...)
- if err != nil && errors.Is(err, orm.ErrNoRows) {
- return o.Insert(md)
- } else if err != nil {
- return 0, err
- }
- return o.Update(md)
- }
|