Skip to content

Instantly share code, notes, and snippets.

@arivictor
Last active February 6, 2021 04:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arivictor/8c3aa938d5f3a91e52ffe3e651a92383 to your computer and use it in GitHub Desktop.
Save arivictor/8c3aa938d5f3a91e52ffe3e651a92383 to your computer and use it in GitHub Desktop.
The completed codebase for the gorm many-to-many project
package main
import (
"fmt"
"gorm.io/gorm"
"log"
)
type User struct {
gorm.Model
Name string `json:"name"`
Skills []Skill `gorm:"many2many:job_skill;"`
}
type Skill struct {
Name string `gorm:"primary_key"`
}
func main() {
// Connect to our local Postgres database
db, err := gorm.Open("postgres", "postgres://localhost:5432/dev?sslmode=disable")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Auto-generates our tables and schema!
err = db.AutoMigrate(&User{}, &Skill{})
if err != nil {
log.Fatal(err)
}
// Create a User
user := &User{
Name: "Ari",
Skills: []Skill{{Name: "Go"}, {Name: "Gorm"}},
}
// Add the user to the database
db.Create(&user)
// Print the users new ID from the database
fmt.Println(user.ID)
package main
import (
"fmt"
_ "github.com/lib/pq"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"log"
)
type User struct {
gorm.Model
Name string `json:"name"`
Skills []Skill `gorm:"many2many:job_skill;"`
}
type Skill struct {
Name string `gorm:"primary_key"`
}
func main() {
db, err := gorm.Open(postgres.New(postgres.Config{
DriverName: "postgres",
DSN: "postgres://localhost:5432/dev?sslmode=disable",
}), &gorm.Config{})
if err != nil {
fmt.Printf("Error: %v\n", err)
}
// Auto-generates our tables and schema!
err = db.AutoMigrate(&User{}, &Skill{})
if err != nil {
log.Fatal(err)
}
// Create a User
user := &User{
Name: "Ari",
Skills: []Skill{{Name: "Go"}, {Name: "Gorm"}},
}
// Add the user to the database
db.Create(&user)
// Print the users new ID from the database
fmt.Println(user.ID)
// Update our users skills
user.Skills = []Skill{{Name: "Python"}, {Name: "JavaScript"}}
// Update user in db EXCEPT skills
db.Omit("Skills").Updates(&user)
// Now update just the Skills
err = db.Session(&gorm.Session{FullSaveAssociations: true}).Model(&user).Association("Skills").Replace(&user.Skills)
if err != nil {
fmt.Println(err)
}
// Print the users new ID from the database
fmt.Println(user.Skills)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment