I have my GORM Schemas shown below. Two tables i.e Items and Users. Every item is has a user who created the item.
type Item struct {
ID uuid.UUID `gorm:"type:uuid;default:gen_random_uuid();primaryKey"`
Title string `gorm:"type:varchar(50)"`
Description string `gorm:"type:varchar(450)"`
CreatorID uuid.UUID `gorm:"type:uuid"`
CreatorUser User `gorm:"foreignKey:CreatorID;references:ID"`
IsDeleted bool `gorm:"type:boolean;default:false"`
}
type User struct {
ID uuid.UUID `gorm:"type:uuid;default:gen_random_uuid();primaryKey"`
Username string `gorm:"type:varchar(100);not null"`
Age int `gorm:"type:int"`
Password string `gorm:"type:varchar(100);"`
Email string `gorm:"type:varchar(50)"`
Bio string `gorm:"type:varchar(450)"`
Role string `gorm:"type:varchar(50)"`
Address string `gorm:"type:varchar(100)"`
State string `gorm:"type:varchar(50)"`
Country string `gorm:"type:varchar(50);not null"`
Balance float64 `gorm:"type:numeric(13,2);default:100.00"`
Currency string `gorm:"type:varchar(4);default:'INR'"`
IsDeleted bool `gorm:"type:boolean;default:false"`
}
When I select the fields using the GORM query below
var item gormSchemas.Item
err = pr.gormDb.Model(&item).Preload("CreatorUser", func(db *gorm.DB) *gorm.DB {
return db.Select("id, username, email, bio, country, is_deleted,date_created")
}).Preload("Organization", func(db *gorm.DB) *gorm.DB {
return db.Select("id, name, bio, location, website")
}).First(&item, "id = ?", itemId).Error
I seem to get the following response
{
"ID": "d4e764e0-f20a-4d45-88a7-c4eff9afbaac",
"Title": "Bluetooth Portable Speaker",
"Description": "Compact and powerful Bluetooth portable speaker with excellent sound quality and a long-lasting battery. Perfect for on-the-go music enjoyment.",
"IsDeleted": false,
"CreatorUser": {
"ID": "b07e0a43-b4e1-4dc5-a317-813a6eaca6b1",
"Username": "blah",
"Age": 0,
"Password": "",
"Email": "[email protected]",
"Bio": "I love coding!",
"Role": "",
"Address": "",
"State": "",
"Country": "USA",
"Balance": 0,
"Currency": "",
"IsDeleted": false,
"IsVerified": false,
"DateCreated": "2024-07-24T09:33:57.829562Z",
"ProfilePictureUrl": "",
"Organizations": null,
"LastLoggedIn": "2024-07-24T09:33:57.829562Z"
},
}
The problem is that I do not want to fetch fields like password, role, balance, currency from users table when joining. The fields should not appear at all.
I tried omitting the fields using the query below but the field still appears albeit empty
pr.gormDb.Preload("CreatorUser", func(db *gorm.DB) *gorm.DB {
return db.Omit("Password", "Role","Balance").Select("id, username, email, bio, country, is_deleted, is_verified, date_created, profile_picture_url, last_logged_in")
}).