Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gorm Many To Many Select gives 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 am expecting this result:

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

But I am getting invalid association [] on console, adding a gorm logger did not provide more information.

Even if I can only get a "languages" object like an array of languages names, this is also fine:

"languages" : ["eng", "man"]
like image 952
Nitin Avatar asked Jan 07 '16 23:01

Nitin


2 Answers

You may try:

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

More examples can be find in the test

like image 110
Eagle Avatar answered Nov 15 '22 19:11

Eagle


I think you need to use Association. You can also get the matching user more succinctly using 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
}
like image 1
Charlie Egan Avatar answered Nov 15 '22 20:11

Charlie Egan