Skip to content

Instantly share code, notes, and snippets.

@albttx
Created December 13, 2017 15:49
Show Gist options
  • Save albttx/6dc85f47db2f36f68ea79ec0ff1424b6 to your computer and use it in GitHub Desktop.
Save albttx/6dc85f47db2f36f68ea79ec0ff1424b6 to your computer and use it in GitHub Desktop.
Golang GORM has_many exemple
package main
import (
"fmt"
"log"
"github.com/Sirupsen/logrus"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
var (
DB *gorm.DB
)
type Topic struct {
gorm.Model
// TopicID uint `gorm:"primary_key"`
Name string
Posts []Post `gorm:"ForeignKey:ID"`
}
type Post struct {
gorm.Model
// PostID uint `gorm:"primary_key"`
Title string
TopicRefer uint `gorm:"column:id`
}
func main() {
var err error
dbConnect()
// DB.LogMode(true)
defer DB.Close()
DB.AutoMigrate(&Topic{}, &Post{})
model := Topic{}
// DB.Model(&model).Related(&model.Posts, "TopicRefer")
DB.Model(&model).Related(&model.Posts, "TopicRefer")
defer DB.DropTable(&Topic{}, &Post{})
DB.LogMode(true)
// Create Topic Finance
t := &Topic{Name: "Finance"}
err = DB.Model(&Topic{}).Create(t).Error
if err != nil {
log.Fatal("Error creating topic finance: ", err)
}
// Create Post about blockchain
p := &Post{Title: "blockchain", TopicRefer: 1}
// Associate Post to Topic
res := DB.Model(t).Association("Posts").Append(p)
if res.Error != nil {
log.Fatal("Can't attach post to topic: ", res.Error)
}
fmt.Printf(" Associate post to topic: %+v\n", res)
// Get first Topic
topic := Topic{}
err = DB.Model(topic).First(&topic).Related(&topic.Posts, "TopicRefer").Error
if err != nil {
log.Fatal("Error getting topic: ", err)
}
// Print Topic
fmt.Println("Topics: ", topic, topic.Posts)
if len(topic.Posts) > 0 {
fmt.Println("\n\n------ ITS WORKED !!!!! ------")
}
DB.LogMode(false)
}
func dbConnect() {
var err error
logrus.Print("DB connecting...")
pgURL := fmt.Sprintf("postgresql://%s:%s@%s:%s/%s?sslmode=%v", "dev", "dev", "172.16.239.135",
"5432", "dev", "disable")
DB, err = gorm.Open("postgres", pgURL)
if err != nil {
logrus.Fatal("Error connecting postgres: ", err)
}
logrus.Print("DB connected")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment