8

这是我的数据库架构:

用户:

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"]
4

2 回答 2

10

你可以试试:

db.Model(&user).Related(&languages, "Languages") 

更多示例可以在测试中找到

于 2016-06-23T04:50:19.377 回答
1

我认为你需要使用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
}
于 2016-01-08T22:55:15.887 回答