英文:
How do I use custom preload in gorm
问题
我有这两个结构体:
type User struct {
gorm.Model
Name string
CompanyID int
Company Company
}
type Company struct {
gorm.Model
Name string
Adress string
}
我想获取用户并预加载他们的公司,但我不想获取地址字段。我尝试了下面的自定义预加载方式,并在Postman中进行了测试。查询返回了所有字段,但是地址字段返回了一个空字符串。这是因为在将结果存储在用户结构体中时,Golang会自动初始化所有字段,而地址字段返回的是其初始值,即空字符串。
var user []User
db.Table("users").Preload("Company", func(db *gorm.DB) *gorm.DB {
return db.Select("ID", "Name")
}).Find(&user)
我应该怎么做才能只获取名称和ID,而不获取地址?
英文:
I have these 2 structs
type User struct {
gorm.Model
Name string
CompanyID int
Company Company
}
type Company struct {
gorm.Model
Name string
Adress string
}
I want to get users and preload their companies but I don't want to get the Adress field I tried the custom preload like bellow and I tested it in postman . the query returned all the fields but for adress I get an empty string , the reason why this is happening is that when storing the result in the user struct golang automatically initialize all the fields and the field adress get returned with its initial value which is an empty sting
var user []User
db.Table("users").Preload("Company",func(db *gorm.DB) *gorm.DB {
return db.Select("ID" ,"Name")
}).Find(&user)
what should I do to only have the name and id but not the adress
答案1
得分: 1
如果你的服务器将结果导出为 JSON,你可以使用 json 标签 omitempty 来添加。代码如下:
type Company struct {
gorm.Model
Name string
Adress string `json:"omitempty"`
}
这样,如果地址字段是空字符串,它将不会被包含在内。
英文:
If your server exports the result as json you could add the json tag omitempty as such:
type Company struct {
gorm.Model
Name string
Adress string `json:"omitempty"`
}
That way the address field will not be included if it is an empty string.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论