-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser_update.go
62 lines (51 loc) · 2.17 KB
/
user_update.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package controller
import (
"context"
"time"
"demo/model"
"github.com/forbearing/golib/database"
"github.com/gin-gonic/gin"
)
func (u *user) Update(c *gin.Context) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
user := new(model.User)
users := make([]*model.User, 0)
// Update single User record
// NOTE: User.ID field must be set - records are update based on ID
// All fields will be updated.
database.Database[*model.User]().Update(user)
database.Database[*model.User](ctx).Update(user)
// Batch update user records in database.
// NOTE: ID field must be set for each user record.
// All fields will be updated.
database.Database[*model.User]().Update(users...)
database.Database[*model.User](ctx).Update(users...)
// Update user records without batch size limit.
database.Database[*model.User]().WithLimit(-1).Update(users...)
// Update user records with batch size of 100.
// It's useful when the User model contains so many fields.
database.Database[*model.User]().WithLimit(100).Update(users...)
// Update users without triggering model's hooks.
// It's useful to break recursive model hook triggers.
database.Database[*model.User]().WithoutHook().Update(user)
database.Database[*model.User]().WithoutHook().Update(users...)
// Update users with all fields but except 'email' and 'avatar'.
database.Database[*model.User]().WithOmit("email", "avatar").Update(user)
database.Database[*model.User]().WithOmit("email", "avatar").Update(users...)
// Update Single User record.
// Only update `name` field.
// NOTE: UpdateById will not trigger model's hooks.
//
// SQL equivalent:
// UPDATE users
// SET name = 'new_name'
// WHERE id = 'my_user_id'
// AND name = 'old_name'
database.Database[*model.User]().UpdateById("my_user_id", "old_name", "new_name")
database.Database[*model.User](ctx).UpdateById("my_user_id", "old_name", "new_name")
// =====================================================================
// Why choose database.Database().Create/Delete/Update/List/Get methods:
// beacause model's hooks only invoke in database.Database.
// =====================================================================
}