这是我的数据库架构:
用户:
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"]
忽然笑
哔哔one
相关分类