AdSense

網頁

2022/11/30

Golang GORM model table name mapping

GORM model名稱與資料表名稱的映射。


GORM慣例是modelCamelCase名稱對應到資料表snake_cases複數名稱,例如model Employee對應到資料表employees

若不符以上慣例,model可實作Tabler介面的TableName方法來設定model對應的資料表名稱。

例如下面設定model Employee屬性對應到資料表employee

type Employee struct {
    ID        int64     // column name is `id`
    Name      string    // column name is `name`
    Age       int       // column name is `age`
    CreatedAt time.Time // column name is `created_at`
}

func (emp Employee) TableName() string {
    return "employee" // 設定Employee對應資料表名稱為"employee"
}

或是在呼叫gorm.Open傳入NamingStrategy.SingularTable為true,則Employee對應到資料表employee

const (
    HOST     = "localhost"
    PORT     = "5432"
    DATABASE = "postgres"
    USER     = "admin"
    PASSWORD = "12345"
    SSL      = "disable"
)

func getGormDB() *gorm.DB {
    dsn := fmt.Sprintf(
        "host=%s port=%s user=%s password=%s dbname=%s sslmode=%s",
        HOST, PORT, USER, PASSWORD, DATABASE, SSL)

    gormDB, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
        NamingStrategy: schema.NamingStrategy{
            SingularTable: true, // use singular table name, table for `Employee` would be `employee` with this option enabled
        },
    })
    if err != nil {
        panic("open gorm db error")
    }

    return gormDB
}



沒有留言:

AdSense