问题
While creating primary key from gorm model it return with error “duplicate column name: “id””
my model looks like
type User struct {
gorm.Model
Id string gorm:"primary_key;"
FirstName string
LastName string
}
any idea what is the issue with above model
回答1:
Gorm uses ID as the primary key by default. It is part of the gorm.Model
you are embedding.
When embedding the gorm.Model
, you should leave ID
out as gorm already includes it. The alternative is to remove the embedded gorm.Model
and specify ID
yourself.
To quote the gorm conventions page:
gorm.Model is a basic GoLang struct which includes the following fields: ID, CreatedAt, UpdatedAt, DeletedAt.
It may be embeded into your model or you may build your own model without it.
The reasons this fails on schema creation as opposed to compilation is that a lot of databases (CockroachDB included) do case insensitive checking unless you quote the object names (Id
matches id
, but "Id"
does not). This results in two separate column names that match when compared with case insensitivity.
来源:https://stackoverflow.com/questions/56735451/issue-while-creating-primary-key-from-gorm-model