Home > Backend Development > Golang > db.Model(&Usertable).Create(data): How to pass the correct table name?

db.Model(&Usertable).Create(data): How to pass the correct table name?

PHPz
Release: 2024-02-08 22:15:08
forward
643 people have browsed it

db.Model(&Usertable).Create(data): How to pass the correct table name?

When using Golang for database operations, we often use code like `db.Model(&Usertable).Create(data)` to create new data. However, sometimes we may encounter a problem: how to pass the correct table name? In this article, PHP editor Youzi will answer this question in detail to help readers better understand how to correctly pass the table name for smooth database operations.

Question content

I am trying to insert a row into a table defined as a model. The following are relevant code snippets:

Package structure:

gorm
|- server
   |- insertRow.go
|- pkg
   |- models
      |- mytable.go
   |- database
      | - connectdb.go
Copy after login

mytable.go:

package models

type Usertable struct {
    Firstname    string `gorm:"column:firstname"`
    Lastname  string `gorm:"column:lastname"`
}

func (fmap *Usertable) TableName() string { return "usertable" }
Copy after login

insertRow.go

package main
import (
        "fmt"
       "gorm/pkg/models"
        "gorm/pkg/database"
)

func  main() {
  params := map[string]interface{} {
        "Firstname" : "MyFirstName",
        "Lastname" : "LastName" ,
 }
        db, _ := database.NewStorage("postgres", "testdb")

        var user models.Usertable

        err := db.DB.Debug().Model(&user).Create(params)
        if err != nil {
                fmt.Println("Error :=", err)
        } else {
                fmt.Println("Success")
        }

}
Copy after login

Table definition:

testdb=# \d+ usertable
                                 Table "public.usertable"
  Column   | Type | Collation | Nullable | Default | Storage  | Stats target | Description
-----------+------+-----------+----------+---------+----------+--------------+-------------
 firstname | text |           |          |         | extended |              |
 lastname  | text |           |          |         | extended |              |
Copy after login

The following error will occur when executing insertRow.go:

(/root/gorm/cloudOps/server/testDB/insertRow.go:17)
[2023-09-23 23:51:26]  pq: zero-length delimited identifier at or near """"

(/root/gorm/cloudOps/server/testDB/insertRow.go:17)
[2023-09-23 23:51:26]  [0.45ms]  **INSERT INTO "" DEFAULT VALUES RETURNING "".***
[0 rows affected or returned ]
Error := &{{{0 0} 0 0 {{} 0} {{} 0}} map[Firstname:MyFirstName Lastname:LastName] pq: zero-length delimited identifier at or near """" 0 0xc0000a4b60 false 2 {0xc0001a3d60} 0xc0001e8420 {{0 0} {[] {} 0xc00021cc20} map[] 0} 0xc0000a4c30 <nil> 0xc0000a2c78 false <nil>}
Copy after login

The table name in the insert command seems to be empty, please let me know what is wrong with my insert command and how can I pass the correct table name to the Create call.

I also tried it, with the same result:

package main
import (
    "fmt"
//       "gorm/pkg/models"
    "gorm/pkg/database"
    "gorm.io/gorm"
)

type Usertable struct {
    gorm.Model
    Firstname    string `gorm:"column:firstname"`
    Lastname  string `gorm:"column:lastname"`
}

func  main() {
  params := map[string]interface{} {
    "Firstname" : "MyFirstName",
    "Lastname" : "LastName" ,
 }
    db, _ := database.NewStorage("postgres", "testdb")


    err := db.DB.Debug().Model(&Usertable{}).Create(params)
    if err != nil {
        fmt.Println("Error :=", err)
    } else {
        fmt.Println("Success")
    }

}
Copy after login

Workaround

You set up a map[string]interface{} to insert, but gorm expects to be passed a structure

user := models.Usertable{
    Firstname: "MyFirstName",
    Lastname:  "LastName",
}

result := db.DB.Debug().Create(&user)
Copy after login

The above is the detailed content of db.Model(&Usertable).Create(data): How to pass the correct table name?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template