gpt4 book ai didi

go - 如何获得多对多的数据关联

转载 作者:IT王子 更新时间:2023-10-29 02:18:47 31 4
gpt4 key购买 nike

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

我有 struct User、Event、Event Review。事件与用户有多对多的关系。我读过 gorm 文档协会 Gorm associaton many to many但我混淆了从事件回顾中获取数据。

结果打印:

&{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
}

关于go - 如何获得多对多的数据关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56815932/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com