我现在在使用 Gorm 从数据库(Postgres)获取数组提要的 id 时遇到问题。
如何查询并返回 id 数组 feed?我不知道如何在没有循环的情况下从结构中仅获取 id
feeds := []models.Feed{}
feedID := []string{}
db.Select("id").Where("user_id = ?", "admin1").Find(&feeds)
for _, feed := range feeds {
feedID = append(feedID, feed.ID)
}
utils.PrintStruct(feeds)
Run Code Online (Sandbox Code Playgroud)
这是 feed 模型文件:
type Feed struct {
Model
Status string `json:"status"`
PublishAt *time.Time `json:"publishAt"`
UserID string `json:"userID,omitempty"`
}
Run Code Online (Sandbox Code Playgroud)
这是用于数据实体的模型基础数据模型:
type Model struct {
ID string `json:"id" gorm:"primary_key"`
}
Run Code Online (Sandbox Code Playgroud)
结果:
[
{
"id": "d95d4be5-b53c-4c70-aa09",
"status": "",
"publishAt": null,
"userID":""
},
{
"id": "84b2d46f-a24d-4854-b44d",
"status": "",
"publishAt": null,
"userID":""
}
]
Run Code Online (Sandbox Code Playgroud)
但我想要这样的:
["d95d4be5-b53c-4c70-aa09","84b2d46f-a24d-4854-b44d"]
Run Code Online (Sandbox Code Playgroud)
你可以用拔力
var ids []string
db.Model(&Feed{}).Where("user_id = ?", "admin1").Pluck("id", &ids)
Run Code Online (Sandbox Code Playgroud)