如何获得多对多数据关联

时间:2019-06-29 07:47:33

标签: go go-gorm

我是Gorm协会的新成员。我有这样的代码:

package main

import (
    _ "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
    "github.com/jinzhu/gorm"
)

type User struct {
    ID   uint `gorm:"primary_key"`
    Name string
}

type Event struct {
    ID        uint `gorm:"primary_key"`
    EventName string
    Users     []User `gorm:"many2many:event_reviews;"`
}

type EventReview struct {
    UserID  uint
    EventID uint
    Rating  float64
    Review  string
}

func main() {
    db, _ := gorm.Open("mysql", "root:@tcp(127.0.0.1:3306)/test1?charset=utf8&parseTime=True")
    defer db.Close()
    db.DropTableIfExists(&EventReview{}, &Event{}, &User{})
    db.AutoMigrate(&User{}, &Event{}, &EventReview{})

    //All foreign keys need to define here
    db.Model(EventReview{}).AddForeignKey("user_id", "users(id)", "CASCADE", "CASCADE")
    db.Model(EventReview{}).AddForeignKey("event_id", "events(id)", "CASCADE", "CASCADE")

    user := User{Name: "John"}
    db.Create(&user)
    event := Event{EventName: "Learning Go"}
    db.Create(&event)
    eventReview := EventReview{UserID: user.ID, EventID: event.ID, Rating: 2.5, Review: "ExcelentEvent"}
    db.Create(&eventReview)

    //Fetching
    eventFetch := &Event{}
    db.Preload("Users").First(&eventFetch)
    fmt.Println(eventFetch)
}

我有结构用户,事件,事件查看。事件与用户之间有很多关系。我已经阅读了gorm docs associaton Gorm associaton many to many,但是我混淆了从事件审查获取数据。

结果打印标签:

&{1 Learning Go [{1 John}]}

预期结果:

&{1 Learning Go [{1 John 2.5 ExcelentEvent}]}

如何获得预期的结果?我使用多对多关系表错了吗?

1 个答案:

答案 0 :(得分:0)

使用相关方法:

WriteHeader