Home > database >  gorm primary key dont appear in database
gorm primary key dont appear in database

Time:09-16

im a beginner in golang. when im using gorm:"primaryKey" enter image description here

i dont see any field that use primary key

this is my model

type Orders struct {
    OrderID      uint64    `gorm:"primaryKey" json:"orderId"`
    CustomerName string    `json:"customerName"`
    OrderedAt    time.Time `json:"orderedAt" example:"2020-01-09T21:21:46 00:00"`
    Items        []Items   `json:"items"`
}

type Items struct {
    ItemID      uint64 `gorm:"primaryKey" json:"lineItemId"`
    Item_code   string `json:"itemCode"`
    Description string `json:"description"`
    Quantity    int    `json:"quantity"`
}

which part do i wrong? and do i need relational database for items field?

CodePudding user response:

Lets be clear over here, At first you need to declare a struct as a Model i.e by

type Anything struct {
    gorm.Model
    ... (other fields)
}

And then in order to use Has Many relation you need to use the ID of the parent on the child i.e

type User struct {
  gorm.Model
  CreditCards []CreditCard
}

type CreditCard struct {
  gorm.Model
  Number string
  UserID uint    (like this over here.)
}

Please do kindly follow the docs GORM Docs

CodePudding user response:

In the model Orders model has a hasMany relation to Items, but Items is missing the Key of Orders.

The db.AutoMigrate(&models.Orders{}, &models.Items{}) should be failing to create in this case for Order.Items, but the error is ignored.

Include OrdersID in Items struct to complete referential integrity because gorm expects default primary key/ foreign key as <StructName>ID so for Orders it will search OrdersID in Items

type Orders struct {
  OrdersID      uint64    `gorm:"primaryKey" json:"orderId"`
  ...
}

type Items struct {
  OrdersID uint64
  ...
}

Suggestion, structs should be called Order and Item rather than Orders and Items thus the model becomes

type Order struct {
    OrderID      uint64    `gorm:"primaryKey" json:"orderId"`
    CustomerName string    `json:"customerName"`
    OrderedAt    time.Time `json:"orderedAt" example:"2020-01-09T21:21:46 00:00"`
    Items        []Item    `json:"items"`
}

type Item struct {
    ItemID      uint64 `gorm:"primaryKey" json:"lineItemId"`
    Item_code   string `json:"itemCode"`
    Description string `json:"description"`
    Quantity    int    `json:"quantity"`
    OrderID     uint64
}

  • Related