-
-
Save lordnynex/d14164553f07b8b8c7ab58d72ce84296 to your computer and use it in GitHub Desktop.
Golang GORM has_many exemple
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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