gorm updates
时间: 2023-09-26 12:11:54 浏览: 122
GORM is a popular object-relational mapping (ORM) library for the Go programming language. It provides a convenient way to interact with databases by abstracting the underlying SQL operations. To perform updates using GORM, you can use the `Update` or `Model` functions.
The `Update` function allows you to update specific attributes of a model based on certain conditions. Here's an example:
```go
db.Model(&User{}).Where("id = ?", 1).Update("name", "John Doe")
```
This code snippet updates the `name` attribute of the `User` model with the ID of 1, setting it to "John Doe".
If you want to update multiple attributes at once, you can pass a map to the `Update` function:
```go
db.Model(&User{}).Where("id = ?", 1).Updates(map[string]interface{}{"name": "John Doe", "age": 30})
```
In this case, both the `name` and `age` attributes of the `User` model with the ID of 1 will be updated.
Alternatively, you can use the `Model` function to update a model instance directly:
```go
user := User{ID: 1}
db.Model(&user).Updates(User{Name: "John Doe", Age: 30})
```
This updates the `name` and `age` attributes of the `user` instance in the database.
These are just a few examples of how you can perform updates using GORM. The library provides many more features and options for working with databases in Go.
阅读全文