这是我的数据库架构:
用户:
id uuid PRIMARY KEY , title character "1234" "ABCD"
语言:
id uuid PRIMARY KEY , name character "1122" "eng" "1133" "man"
user_languages:
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 logger没有提供更多信息.
即使我只能获得像语言名称数组这样的"语言"对象,这也很好:
"languages" : ["eng", "man"]
Eagle.. 7
你可以尝试:
db.Model(&user).Related(&languages, "Languages")
在测试中可以找到更多示例
你可以尝试:
db.Model(&user).Related(&languages, "Languages")
在测试中可以找到更多示例