-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate.go
33 lines (29 loc) · 872 Bytes
/
create.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package gormhelper
import (
"context"
"errors"
"gorm.io/gorm"
"strings"
)
const DUPLICATE_ENTRY = "Duplicate entry"
// Create 创建数据
func Create[T Model](db *gorm.DB, ctx context.Context, data *T, opts ...Option) error {
err := ApplyOptions[T](db, ctx, opts...).Create(data).Error
if err != nil {
if options := NewOptions(opts...); options.Ignore && strings.Contains(err.Error(), DUPLICATE_ENTRY) {
return nil
}
return err
}
return nil
}
// FirstOrCreate 查询指定表的第一行数据, 如果不存在则创建
func FirstOrCreate[T Model](db *gorm.DB, ctx context.Context, defaultData *T, opts ...Option) (data *T, err error) {
if data, err = FirstWithoutIgnore[T](db, ctx, opts...); err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return defaultData, Create(db, ctx, defaultData)
}
return nil, err
}
return data, nil
}