'How can I check the data generated by gorm raw statement?
I created data with golang gorm, I need to form a relationship in another table based on the generated data id, but I don't know how to check the generated data, how can I check the generated data?
func DefaultMapCreate(userId uint) *model.Map {
var temp model.Map
db.Raw("INSERT INTO maps(title, location, created_at, updated_at) VALUES (?, ?, ?, ?)", "default", "test", time.Now(), time.Now()).Scan(&temp)
return &temp
}
I want to put the data generated in the code above into &temp and generate other data in the same function based on it.
But I can't create relational data because I don't know how to get the generated data back. Please help!, I need id value for generated data, id value is auto increment type
Solution 1:[1]
I would suggest to use gorm.Create() . You can look at the useful information of Declaring gorm models from here.
type MyMap struct {
ID uint `gorm:"primaryKey"`
Title string
Location string
CreatedAt Time
UpdatedAt Time
}
func DefaultMapCreate(userId uint) {
record := MyMap{
Title: "default",
Location: "",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
result := db.Create(&record) // pass pointer of data to Create
//record.ID // returns inserted data's primary key
//result.Error // returns error
//result.RowsAffected // returns inserted records count
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
