How to use Enums with GORM!

Introduction to enums in GORM:

GORM is a popular Go ORM that allows us to define structs to represent database tables and provides an interface to perform CRUD operations. Enums are a useful feature in programming that allows us to define a fixed set of values that a variable can take. In this article, we will explore how to add an enum to a GORM model.

Step 1: Define the Enum

First, we need to define the enum type. In Go, we can use the string type to define enums. Here is an example:

type Status string

const (
    Pending Status = "pending"
    Approved Status = "approved"
    Rejected Status = "rejected"
)

In the above example, we have defined an Status enum with three possible values: "pending", "approved", and "rejected".

Step 2: Define the Model

Next, we need to define a GORM model that uses the enum type. Here is an example:

type User struct {
    ID        uint   `gorm:"primary_key"`
    Name      string
    Status    Status
    CreatedAt time.Time
    UpdatedAt time.Time
}

In the above example, we have defined a User model with a Status field of type Status.

Step 3: Use Enum in GORM Operations

Now that we have defined the enum type and the GORM model, we can use the enum in GORM operations. Here are some examples:

// Create a new user with status "pending"
user := User{Name: "John", Status: Pending}
db.Create(&user)

// Query all users with status "approved"
var users []User
db.Where("status = ?", Approved).Find(&users)

// Update a user's status to "rejected"
db.Model(&user).Update("status", Rejected)

// Delete all users with status "pending"
db.Where("status = ?", Pending).Delete(User{})

In the above examples, we have used the Status enum in GORM operations like creating, querying, updating, and deleting records.

Option 1: String Type

One option to represent enums is to use a string type for the field in the model. Here is an example:

type User struct {
  ID   uint
  Role string
}

You can use this string field to represent the different roles for the user, for example, "admin", "moderator", "user", etc.

However, there are some disadvantages to this approach. For instance, it is easy to make typos, and there is no way to restrict the values to a predefined set.

Option 2: Custom Types

Another option is to use custom types to represent the enum values. Here is an example:

type Role string

const (
  Admin     Role = "admin"
  Moderator Role = "moderator"
  User      Role = "user"
)

type User struct {
  ID   uint
  Role Role
}

In this example, the Role type is defined as a string. Then, the different values are declared as constants. Finally, the Role type is used for the Role field in the User model.

This approach has some advantages. For example, it provides compile-time checking, so it is harder to make typos. Also, it restricts the values to a predefined set.

Option 3: Using GORM's Enums

GORM provides a built-in type for enums that can be used in the model definition. Here is an example:

type Role string

const (
  Admin     Role = "admin"
  Moderator Role = "moderator"
  User      Role = "user"
)

type User struct {
  ID   uint
  Role Role `gorm:"type:enum('admin', 'moderator', 'user')"`
}

In this example, the Role type and constants are defined as in the previous example. However, in the User model, the Role field is annotated with a gorm:"type:enum('admin', 'moderator', 'user')" tag.

This approach provides the same advantages as the previous one, but it also has the advantage that GORM will create the database table with the enum type.

Conclusion:

In this article, we have explored how to add an enum to a GORM model in Go. Enums are a useful feature that allows us to define a fixed set of values that a variable can take. By using enums in GORM models, we can improve the type safety of our code and make our database operations more reliable.

I hope this helps, you!!

More such articles:

https://medium.com/techwasti

https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA

https://www.techwasti.com/

\==========================**=========================

If this article adds any value to you then please clap and comment.

Let’s connect on Stackoverflow, LinkedIn, & Twitter.

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!