如何使数据协会成为许多人



我是GO 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)
}

我有结构用户,事件,事件审核。事件与用户有很多关系。我已经阅读了许多人读过许多人,但我感到困惑以获取事件审查的数据。

结果println:

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

结果预期:

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

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

使用相关方法:

db.Model(&dm.User{}).Related(&dm.EventReview{}, "user_id")
res:=QueryByStructExample(dm.User{Email: "email@example.com})

 func QueryByStructExample(userStruct User) []User {
        var results []dm.User
        GormDB.Where(userStruct).Find(&results)
        return results
    }

相关内容

  • 没有找到相关文章

最新更新