Your Question
Let's say I have two tables test_user and language, and a many-to-many table test_user_language
type TestUser struct {
ID string `json:"id" gorm:"primaryKey"`
Languages []Language `gorm:"many2many:test_user_language"`
Base
}
type Language struct {
ID string `json:"id" gorm:"primaryKey"`
Name string `json:"name"`
Base
}
I tried to use Preload and Scan together. Like below:
func main(){
cfg, _ := config.Load()
db, _ := dbutil.New(cfg.DbDsn, cfg.DbLog)
var err error
r := []*model.TestUser{}
err = db.Model(&model.TestUser{}).
Preload("Languages").Scan(&r).Error
if err != nil {
panic(err)
}
It seemed not to work. But it worked if I replaced Scan() with Take() or Find(). Can anyone tell me why? I have searched for this but didn't find any document or explanation for this. All the answers would be appreciated! Many thanks 🙏