表的golang ORM名称

I have some code to create the table in 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"}

there are 2 problems, i faced: 1) in database created a table "tables" instead of "Table" 2) how can I insert data in existing another tables? (for example "users")

2个回答



1)您可以将Table的表名设置为 table </ code> </ p>

  func(表)TableName()字符串{
返回“表”
}
</ code> </ pre>

另一种方法是将singularTable设置为true,然后将 Table </ code>的默认表名将是 table </ code>,而不是 tables </ code>。 但这会影响所有表。</ p>

 设置数据库。SingularTable(true)
</ code> </ pre>

2)在 您应该定义ORM表对象。 这是一个名为 Table </ code>的结构。 Gorm将在数据库中创建一个名为 tables </ code>的新表,除非您要覆盖表名,可以按照步骤1进行操作。</ p>
</ div>

展开原文

原文

1) You can set Table's table name to be table

func (Table) TableName() string {
    return "table"
}

Another way is to set singularTable true, then Table's default table name will be table instead of tables. But it will affect all tables the same.

set db.SingularTable(true) 

2) In ORM you should define your table object. Here is a struct called Table. Gorm will create a new table called tables in database unless you want to overwrite table's name you can follow step 1.

My solving of this problem:

    db.Table("my_table").CreateTable(&Table{})

    user := &Table{Name: "ololo", Addr: "pololo"}
    db.Table("my_table").Create(user) 

This code creates table my_table as I wanted

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐