Gorm Many To Many Select gives an invalid association error []

This is my db schema:

users:

id uuid PRIMARY KEY , title character "1234" "ABCD" 

Languages:

 id uuid PRIMARY KEY , name character "1122" "eng" "1133" "man" 

user_languages:

 user_id uuid, language_id uuid "1234" "1122" "1234" "1133" 

This is my code:

 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 } 

I expect this result:

 { "id": "1234", "title": "ABCD", "languages" : [{ "id" : "1122", "name" : "eng" },{ "id" : "1122", "name" : "eng" }] } 

But I get invalid association [] on the console, adding that the gorm logger did not provide more information.

Even if I can only get the Languages ​​object, such as an array of language names, this is also fine:

 "languages" : ["eng", "man"] 
+7
go many-to-many go-gorm
source share
2 answers

You can try:

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

Additional examples can be found in test

+7
source share

I think you need to use Association . You can also get a matching user more briefly with 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 } 
+1
source share

All Articles