I have a following model and seems like gorm does not autogenerate the ID for that.
type Customer struct {
gorm.Model
Username string `gorm:"unique;type:varchar(100); NOT NULL;" json:"username"`
Password string `gorm:"type:varchar(100) NOT NULL;" json:"password"`
Email string `gorm:"unique; type:varchar(100) NOT NULL;" json:"email"`
PurchasedProductsId string `gorm:"primaryKey;unique;" json:"purchased_products_id"`
PurchasedProducts Product `gorm:"foreignKey:ID;references:PurchasedProductsId;"`
CreatedAt string `gorm:"uniqueIndex;type:date;" json:"createdAt"`
}
Also there is a method that creates this object.
func (this *Customer) CreateObject(ObjectData struct {
Username string
Password string
Email string
}, Validator BaseModelValidator, PurchasedProducts ...[]Product) (*gorm.DB, []ValidationError) {
ValidatedData, Errors := Validator.Validate(map[string]string{
"Username": ObjectData.Username,
"Email": ObjectData.Email,
"Password": ObjectData.Password,
})
if Errors != nil {
return nil, Errors
}
newCustomer := Customer{
Username: ValidatedData["Username"],
Email: ValidatedData["Email"],
Password: ValidatedData["Password"],
}
Transaction := Database.Model(&customer).Create(&newCustomer)
fmt.Print(Transaction.Error)
return Transaction, []ValidationError{}
When I'm trying to create object it always responds with
models.go:307 ERROR: null value in column "id" violates not-null constraint (SQLSTATE 23502)
[9.030ms] [rows:0] INSERT INTO "customers" ("username","password","email","created_at") VALUES ('TestUser','TestPassword','testEmail@gmail.com','2022-07-31 22:16:05.796') RETURNING "purchased_products_id","id"
ERROR: null value in column "id" violates not-null constraint (SQLSTATE 23502)[GIN]
Am I Need to add ID
Field Directly or there is some dark magic involved?
you need to add the ID field to the customer struct and you need to add a id field to the table customers the type is a bigint