Issue while creating primary key from gorm model

谁说我不能喝 提交于 2020-01-30 12:09:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!