go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
36.59k stars 3.91k forks source link

Many2Many assigns join table's id to related model's id field #420

Closed nkovacs closed 8 years ago

nkovacs commented 9 years ago
type User struct {
    Id int64
    Name string
    Languages []Language `gorm:"many2many:user_languages"`
}

type Language struct {
    Id int64
    Name string
}

user_languages table contains three fields: id (primary key), user_id and language_id (foreign keys)

If I do

var languages []Language

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

the Id field of the Language structs in the languages array will be id the field from the user_languages table, not the id field of the language in the languages table.

The workaround is to add .Select("languages.*"). I did not test this with Preload though.

jinzhu commented 9 years ago

Hi @nkovacs

Thank you for your report, the join table is created manually by yourself?

nkovacs commented 9 years ago

Yes

LiranCohen commented 9 years ago

I used Association() for relationship when looking for 1 which works fine with many2many.

Preload works great with one2many relationships, but I'm getting a "not supported relation" error with many2many Preload.

Wonder if this is the same issue.

djboris9 commented 9 years ago

querying an many2many realation also fails if one of the primary keys is not named "ID". Could you please provide an working example with preloading of an many2many relation as a Gist or playground snippet?

jinzhu commented 8 years ago

Hi @nkovacs

The issue for Related should been fixed for a while, and just pushed a commit to fix the issue with Preload

Thank you.