CRUD operations with GORM
In previous chapters, whenever we wanted to create an entry in the database, we had to write a SQL statement that inserts the data into the table, but that is no longer needed; GORM takes care of all that for us. Let’s start creating a new user using our GORM model.
Creating a user
To create a new user, we simply create an instance of our model and call the Create method:
user := User{
Username: "johndoe",
Password: "password123",
Role: "user",
}
result := db.Create(&user)
if result.Error != nil {
log.Fatal(result.Error)
}
With this simple Create call, we are inserting our User model into the database, but not only that; because we add the gorm.Model embedding, GORM, after creating the record, also automatically sets the ID, CreatedAt, and UpdatedAt fields.
It is very cool, isn’t it? Now, we don’t need all that SQL and the extra boilerplate code; we just create a struct and...