Muhammad Habib
Muhammad Habib

Reputation: 111

Issue while creating primary key from gorm model

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

Upvotes: 0

Views: 1890

Answers (1)

Marc
Marc

Reputation: 21055

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.

Upvotes: 2

Related Questions