乐闻世界logo
搜索文章和话题

How can i add enum in gorm?

1个答案

1

When working with GORM in Go, implementing enumeration typically involves several approaches. GORM does not natively support enum types because Go itself lacks native enum support, but we can simulate enum functionality using certain strategies. Here are some common methods:

Method One: Using Custom Types

  1. Define a custom type: First, define a custom type based on string or int to represent the enumeration values.
  2. Add methods to the type: Implement methods for this type to ensure valid assignments.
  3. Use the custom type in GORM models: Apply this custom enum type as the field type in your GORM models.

Example

Suppose we want to define a 'role' enumeration for users, with values 'Admin' and 'Member'.

go
package main import ( "gorm.io/gorm" "log" ) // Define custom type // ... (code remains the same)

In this example, we define a Role type where the values Admin and Member are represented as Role types. We use Role as the field type in the User model. The Scan and Value methods ensure GORM correctly handles reading and writing this type.

Method Two: Using Constants and Validation

  1. Define constants: Declare a set of constants representing the enumeration values.
  2. Add a field to the model: Include a standard string or int field to store the enumeration value.
  3. Add validation logic: Validate the field value is a valid enumeration value before insertion or update.

Example

Continuing with the role example, we directly use string without defining a new type:

go
package main import ( "gorm.io/gorm" "log" ) const ( RoleAdmin = "Admin" RoleMember = "Member" ) // Define model // ... (code remains the same)

Here, we must manually validate the Role field value in the code to ensure it matches one of the valid enumeration values.

Summary

Although Go and GORM lack native enum support, the above methods effectively implement similar enumeration functionality in GORM, ensuring data validity and integrity. The choice depends on specific use cases and personal preference.

2024年7月31日 00:19 回复

你的答案