I started GORM the other day and stumbled a lot, so I will leave that point.
Overall,
-** GORM urges Naming Convention, so you need to know in advance **
I felt that.
--By default ** Recognize the plural form of Struct name as a table name **
-If you define a Struct named ** Person
** as a Model, the table name will be treated as ** people
.
--Note that it is not persons
- Implement the Table interface to change the table name **
// Tabler is interface of gorm table name
type Tabler interface {
TableName() string
}
// Person is the model of persons
type Person struct {
ID string `gorm:"column:person_id;type:uuid;primaryKey"`
Name string `gorm:"column:name;type:text;not null"`
Weight int
}
// TableName gets table name of Person
func (Person) TableName() string {
return "persons"
}
Suppose you have two models, Order and Person, as shown below.
package model
// Order is the model of orders
type Order struct {
ID string `gorm:"column:order_id;type:uuid"`
PersonID string `gorm:"type:uuid"`
Person Person // `gorm:"foreignKey:PersonID;references:ID"`
}
// Tabler is interface of gorm table name
type Tabler interface {
TableName() string
}
// Person is the model of persons
type Person struct {
ID string `gorm:"column:person_id;type:uuid;primaryKey"`
Name string `gorm:"column:name;type:text;not null"`
Weight int
}
// TableName gets table name of Person
func (Person) TableName() string {
return "persons"
}
If you want to get the Person when you get the Order, use Eager Loading (Preload ("Person")
).
db := postgresql.Connection()
var order model.Order
result := db.Preload("Person").Find(&order)