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

How to specify a struct with a multi-column unique index for Gorm?

1个答案

1

When working with Gorm for Go database development, it's common to define constraints for models, such as unique indexes. For multi-column unique index requirements, you can implement them in Gorm model definitions using the tag.

Here is a concrete example:

go
package main import ( "gorm.io/gorm" "gorm.io/driver/sqlite" ) type Product struct { gorm.Model Code string Price uint } type Order struct { gorm.Model UserID uint ProductID uint OrderPrice uint // Specify UserID and ProductID as a unique index UniqueIndex string `gorm:"uniqueIndex:idx_user_product;index:idx_user_product,unique"` } func main() { db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } // Migrate the schema db.AutoMigrate(&Product{}, &Order{}) }

In the code example above, the Order struct defines a multi-column unique index. This is achieved by applying the uniqueIndex tag to the UniqueIndex field, which encompasses the UserID and ProductID fields. This ensures that in the Order table, the combination of UserID and ProductID is unique.

Additionally, by specifying the index name as idx_user_product, it becomes useful for database management and query optimization. This approach allows you to enforce data integrity at the database level and maintain uniqueness constraints.

In real-world business scenarios, these constraints are highly beneficial, such as preventing duplicate orders for the same product by a single user. By leveraging database constraints, you can prevent these issues at the data level, enhancing data accuracy and reliability.

2024年7月26日 00:58 回复

你的答案