这是我的数据库架构:用户:id uuid PRIMARY KEY , title character"1234" "ABCD"语言:id uuid PRIMARY KEY , name character"1122" "eng""1133" "man"用户语言:user_id uuid, language_id uuid"1234" "1122""1234" "1133"这是我的代码:type User struct { Id uuid.UUID `json:"id" gorm:"primary_key"` Title string `json:"title"` Languages []Language `json:"languages" gorm:"many2many:user_languages;"`}type Language struct { ID uuid.UUID `json:"id" gorm:"primary_key"` Name string `json:"name"`}func GetUser(id string) User { user := User{} languages := Language{} db.Where("id = ?", id).Find(&user) // SELECT * FROM users WHERE 'id' = id; db.Model(&user).Related(&languages) // SELECT * FROM "languages" INNER JOIN "user_languages" ON "user_languages"."language_id" = "languages"."id" WHERE "user_languages"."user_id" = 111 return user}我期待这个结果:{ "id": "1234", "title": "ABCD", "languages" : [{ "id" : "1122", "name" : "eng" },{ "id" : "1122", "name" : "eng" }]}但是我invalid association []在控制台上,添加 gorm 记录器没有提供更多信息。即使我只能得到一个像语言名称数组这样的“语言”对象,这也很好:"languages" : ["eng", "man"]
2 回答
哔哔one
TA贡献1854条经验 获得超8个赞
我认为你需要使用Association. 您还可以使用 更简洁地获取匹配用户db.First(&user, id)。
func GetUser(id string) User {
var user User
db.First(&user, id)
db.Model(&user).Association("Languages").Find(&user.Languages)
return user
}
- 2 回答
- 0 关注
- 249 浏览
添加回答
举报
0/150
提交
取消