-1

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

jub0bs
  • 60,866
  • 25
  • 183
  • 186
Choi yun seok
  • 309
  • 2
  • 15
  • 1
    `how can I check the generated data?` you have to write the instructions that instructs the computer to do what you need. –  Jul 21 '21 at 08:47
  • I haven't started in a while, I don't understand the content of your comment, can I see a simple example? Thanks for your comments – Choi yun seok Jul 21 '21 at 08:50
  • 1
    maybe you dont know about the language and its syntax ? for loops, if / else statements, type declaration and so on. This is unclear in your post, looks likes you have copy pasted some code, ran it, and now you are blocking. –  Jul 21 '21 at 08:51
  • 1
    Why not use `Create` of Gorm? https://gorm.io/docs/create.html – Chetan Jul 21 '21 at 08:52
  • Just want to add with @ChetanRanpariya why not use a struct for `maps` table and use `Create()` ? – Eklavya Jul 21 '21 at 08:54
  • @Choiyunseok what database are you using? – mkopriva Jul 21 '21 at 09:11
  • You can add return id `SQL` and get data by id if you still want to use RawSql – Eklavya Jul 21 '21 at 09:16
  • or maybe you are looking forward to implement unit testing ? –  Jul 21 '21 at 10:39
  • I am using mysql, I want to do raw coding without using gorm create , just to study – Choi yun seok Jul 21 '21 at 13:31

1 Answers1

0

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
}