Is there any way to auto generate UUID with GORM while saving the object in DB in go?
I am having experience with ROR migrations, where ID would be auto generated and PK by default.
Here is my code
Todo.go
package model
type Todo struct {
ID string `json:"id"`
Text string `json:"text"`
Done bool `json:"done"`
}
schema.resolvers.go
func (r *mutationResolver) CreateTodo(ctx context.Context, input model.NewTodo) (*model.Todo, error) {
db, _ := database.connect()
defer db.Close()
todo := &model.Todo{
Text: input.Text,
ID: fmt.Sprintf("%d", rand.Int()), // I don't want to provide ID like this
}
db.Create(&todo)
...
}
models_gen.go
# GraphQL schema example
#
# https://gqlgen.com/getting-started/
type Todo {
id: ID!
text: String!
done: Boolean!
}
input NewTodo {
text: String!
userId: String!
}
type Mutation {
createTodo(input: NewTodo!): Todo!
}
Any help would be really appreciated.
2条答案
按热度按时间vtwuwzda1#
Assuming you're using gorm v2, you can use
hooks
to achieve this. The documentation about hooks is hereIn particular, you can have a look at the
BeforeCreate
hook. Applied on amodel
, it provides a container for a function to be run before the creation in the database as its name state.The GORM documentation also provides an example to generate a UUID when we create a user entity in a database with Gorm, which seems to be what you're looking for:
anauzrmj2#
GORM Hooks is the most obvious solution to generate UUID when creating an object.
But if you want to generate UUID for every object, you could define a base struct and embed it into object structs.
Or just use the GORM plugin next to generate UUID for objects.