Reputation: 59
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")
Upvotes: 1
Views: 3090
Reputation: 5853
By default, the golang Postgres Client will implicitly use the pluralized version of your struct
name[1]. For example
type Student struct {
FirstName string
LastName string
}
// will create a table name `students`
You can override it like the following, depending on what you are using
// Set User's table name to be `profiles`
func (Student) TableName() string {
return "college_students"
}
type Student struct {
tableName struct{} `pg:"college_students,alias:g"``
}
https://gorm.io/docs/conventions.html#Pluralized-Table-Name
Upvotes: 0
Reputation: 59
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
Upvotes: -2
Reputation: 4733
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.
Upvotes: 6