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"]
You may try:
db.Model(&user).Related(&languages, "Languages")
More examples can be find in the test
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With