i need insert 5 rows, with colum ID = 0, but gorm neglect 0 values, how to fix this?
The document you expected this should be explained
Expected answer
package main
import (
"fmt"
"log"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type Records struct {
ID int
Name string
Price float64
}
func main() {
db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{})
if err != nil {
log.Fatalln(err)
}
r := []*Records{}
if !db.Migrator().HasTable(r) {
if err := db.Migrator().CreateTable(r); err != nil {
log.Fatalln(err)
} else {
fmt.Println("create table ok")
records := make([]Records, 5)
for i := range records {
// FIXME i need insert 5 rows, with colum ID = 0, but gorm neglect 0 values
/*
confused output:
create table ok
&[{0 name-0 1.2} {0 name-1 2.2} {0 name-2 3.2} {0 name-3 4.2} {0 name-4 5.2}]
after insert &[{1 name-0 1.2} {2 name-1 2.2} {3 name-2 3.2} {4 name-3 4.2} {5 name-4 5.2}]
rows = 5
item 1 name-0 1.2
item 2 name-1 2.2
item 3 name-2 3.2
item 4 name-3 4.2
item 5 name-4 5.2
*/
records[i] = Records{ID: 0, Name: fmt.Sprintf("name-%v", i), Price: float64(i) + 1.2}
// db.Select("id", "name", "price").Create(&records[i])
}
fmt.Println(&records)
db.Select("id", "name", "price").Create(&records)
fmt.Println("after insert", &records)
}
} else { // has table, do query
gormDb := db.Select("id", "name", "price").Find(&r)
fmt.Println("rows =", gormDb.RowsAffected)
rows, _ := gormDb.Rows()
for rows.Next() {
var id, name, price any
err = rows.Scan(&id, &name, &price)
if err != nil {
log.Println("row scan err", err)
continue
}
fmt.Println("item", id, name, price)
}
}
}
Comment From: guest6379
type Records struct {
RID int
Name string
Price float64
}
I renamed ID to RID to fix this as a workaround, but how to do without renaming the column name?
Comment From: black-06
If gorm:"primaryKey" is not specified, gorm will try to find id field as prioritizedPrimaryField.
So you can avoid "id" as field name or tag the real primaryKey field.
type Records struct {
ID int
Name string `gorm:"primaryKey"`
Price float64
}