R
R
Roman Rakzin2016-02-01 21:29:42
PostgreSQL
Roman Rakzin, 2016-02-01 21:29:42

How to insert/count db values ​​via gorm in golang?

I started using gorm + postresSQL - I follow the instructions stupidly, but it gives errors

type MyList struct {
   Id uint64
   Name  string   
   IsTrue bool
}

connected
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"


db, err := gorm.Open("postgres", "user=Roman password=Roman dbname=DB1  sslmode=disable")  
   if err != nil {
       log.Fatalf("error: %v\n", err)
   }
   db.DB()


   todo := MyList{Id:8888, Name: "Новое имя", IsTrue:false}

   var me MyList
     db.Where("Name = ?", "Новое имя").First(&me)
     fmt.Println(me)

   db.Create(&todo)

   db.NewRecord(todo)

----- he cursed
[35m(pq: relation "my_lists" does not exist)[0m [33m[2016-02-01 18:58:50][0m [31;1m [0m
[35m(pq: relation "my_lists" does not exist)[0m [33m[2016-02-01 18:58:50][0m[31;1m[0m

And someone knows how to get the id of the inserted line through gorm? Or should I immediately store the ID in the +1 variable and insert this variable? (usually, as it were, I learned it like that "INSERT INTO test(value) VALUES($1) RETURNING id"), but I don’t understand gorm yet.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kravchik, 2016-02-21
@rkravchik

You write the Id yourself when you create the model structure:
But it's better, of course, to stick to the gorm conventions:
Leave the ID empty and after Create it will contain the desired number.
I also recommend using the standard base:

Gorm provide a default model struct, you could embed it in your struct
type Model struct {
    ID        uint `gorm:"primary_key"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time
}

type User struct {
    gorm.Model
    Name string
}

As for errors, check for the necessary tables. Or create them with the code above.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question