Points that stumbled on GORM

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.

Recognize the plural form of Model name as a table name

--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"
}

Use Eager Loading to select information in related tables

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)

Recommended Posts

Points that stumbled on GORM
Where I stumbled on SQLite3
An error that stumbled upon learning YOLO on Google Colab
Points that I often get hooked on writing as a MySQL beginner