Your Question
How to select specific filed when I use "Association"? For example, I have two models UserModel and GroupModel:
type UserModel struct {
ID int `json:"id" gorm:"primaryKey"`
Username string `gorm:"type:varchar(30);uniqueIndex"`
Name string `json:"name"`
Password string `json:"-"`
Validation string `json:"-"`
Status int `json:"status"`
CreatedAt time.Time `gorm:"autoCreateTime"`
LastLogin time.Time
JoinedGroups []UserModel `gorm:"many2many:group_members;"`
}
type GroupModel struct {
ID int `json:"id" gorm:"primary_key"`
Name string `json:"name"`
Desc string `json:"desc"`
CreatedAt time.Time `gorm:"autoCreateTime"`
OwnerID int
Owner UserModel `gorm:"Foreignkey:OwnerID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
Members []UserModel `gorm:"many2many:group_members;"`
}
I want to query a group's members, but I just wan to query the members's id and name,I try to use dao.DB.Model(&group).Association("Members").Select("id,name").Find(&group.Members), but it is error "Select undefined (type *gorm.Association has no field or method Select" .
The document you expected this should be explained
The document tells me how to use Selecting-Specific-Fields and Find-Associations, what I want to know is how to use both of them at the same time.
Expected answer
I just wan to know how can I select just some specific fields when I use Association()?We can use the example I mentioned for illustration.
Comment From: a631807682
Association() return *Association not *DB, and it not support Select.
But it use same *DB to find, so it same to
dao.DB.Model(&group).Select("id,name").Association("Members").Find(&group.Members)
Comment From: li1553770945
Thank you.Actually, I have tried this before, but I wrongly assumed that it did not work.