Advertisement
Guest User

Untitled

a guest
Mar 21st, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.03 KB | None | 0 0
  1. [2017-03-21 21:14:41]
  2.  
  3.  
  4.  
  5. package main
  6.  
  7. import (
  8.     "fmt"
  9.  
  10.     "github.com/jinzhu/gorm"
  11.     _ "github.com/mattn/go-sqlite3"
  12. )
  13.  
  14. type Place struct {
  15.     Id     int
  16.     Name   string
  17.     Town   Town  `gorm:"ForeignKey:TownCode"`
  18.     TownCode int
  19. }
  20.  
  21. type Town struct {
  22.     Id   int
  23.     Name string
  24. }
  25.  
  26. func main() {
  27.     db, _ := gorm.Open("sqlite3", "./data.db")
  28.     defer db.Close()
  29.  
  30.     db.CreateTable(&Place{})
  31.     db.CreateTable(&Town{})
  32.     t := Town{
  33.         Name: "TestTown",
  34.     }
  35.  
  36.     p1 := Place{
  37.         Name:   "Test",
  38.         TownCode: 1,
  39.     }
  40.  
  41.     p2 := Place{
  42.         Name:   "Test2",
  43.         TownCode: 1,
  44.     }
  45.  
  46.     err := db.Save(&t).Error
  47.     err = db.Save(&p1).Error
  48.     err = db.Save(&p2).Error
  49.     if err != nil {
  50.         panic(err)
  51.     }
  52.  
  53.     places := []Place{}
  54.     err = db.Find(&places).Error
  55.     for i, _ := range places {
  56.         db.Model(places[i]).Related(&places[i].Town)
  57.     }
  58.     if err != nil {
  59.         panic(err)
  60.     } else {
  61.         fmt.Println(places)
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement