gorm Many To Many Select给出无效的关联[]错误

时间:2016-01-07 23:42:37

标签: go many-to-many go-gorm

这是我的数据库架构:

用户:

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

2 个答案:

答案 0 :(得分:7)

您可以尝试:

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

可以在test

中找到更多示例

答案 1 :(得分: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
}