golang ORM 表名称

Сер*_*сов 1 postgresql orm go

我有一些代码可以在 Postgres DB 中创建表

import (
    "github.com/jinzhu/gorm"
    _ "github.com/lib/pq"
)
type Table struct {
    Id   int    `gorm:"primary_key"`
    Name string `gorm:"type:varchar(100)"`
    Addr string `gorm:"type:varchar(100)"`
}
func main() {
    db, _ := gorm.Open("postgres", "user=postgres password=poilo777 dbname=mydb sslmode=disable")
    defer db.Close()
    db.CreateTable(&Table{}) 
    user := &Table{Name: "ololo", Addr: "pololo"}
Run Code Online (Sandbox Code Playgroud)

我面临两个问题:1)在数据库中创建了一个表“tables”而不是“Table”2)如何在现有的另一个表中插入数据?(例如“用户”)

Ahm*_*hem 6

1)您可以将Table的表名设置为table

func (Table) TableName() string {
    return "table"
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是将singleTable设置为true,那么Table默认表名将table代替tables。但它会对所有表产生相同的影响。

set db.SingularTable(true) 
Run Code Online (Sandbox Code Playgroud)

2) 在 ORM 中你应该定义你的表对象。这是一个名为 的结构Table。Gorm 将在数据库中创建一个名为的新表,tables除非您想覆盖表的名称,您可以按照步骤 1 操作。