With gorm, is it currently possible to create a UNIQUE constraint across multiple columns?
(It's the case where I don't think I want to make a composite primary key, but I do want to ensure some set of columns are unique together)
This will work:
type Language struct {
ID int
Name string `gorm:"unique_index:idx_name_code"` // Create index with name, and will create combined index if find other fields defined same name
Code string `gorm:"unique_index:idx_name_code"` // `unique_index` also works
}
Awesome, thank you!
Shouldn't this be added to the documentation? I couldn't find anything on the subject.
Do db.Model(&User{}).AddUniqueIndex("idx_user_name_age", "name", "age") as shown on Migrations behaves in the same way as the code shown by @klniu?
How can you control the order of the keys in the index? For instance I believe this will be an index of name, code. What if you wanted it to be code, name?
Most helpful comment
This will work: