How can I query and return only id array by GORM?

huangapple go评论99阅读模式
英文:

How can I query and return only id array by GORM?

问题

我现在遇到一个问题,无法从数据库(Postgres)中使用Gorm获取数组feeds的id。

我该如何查询并返回id数组feeds?我不知道如何在不使用循环的情况下仅获取结构体中的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)

这是feed模型文件:

type Feed struct {
    Model
    Status     string      `json:"status"`
    PublishAt  *time.Time  `json:"publishAt"`
    UserID     string      `json:"userID,omitempty"`
}

这是用于数据实体的基本数据模型:

type Model struct {
    ID        string     `json:"id" gorm:"primary_key"`
}

结果:

[
    {
        "id": "d95d4be5-b53c-4c70-aa09",
        "status": "",
        "publishAt": null,
        "userID": ""
    },
    {
        "id": "84b2d46f-a24d-4854-b44d",
        "status": "",
        "publishAt": null,
        "userID": ""
    }
]

但我想要这样的结果:

["d95d4be5-b53c-4c70-aa09","84b2d46f-a24d-4854-b44d"]
英文:

I'm now having a problem with getting an id of array feeds from database (Postgres) with Gorm.

How can I query and return id array feeds? I don't know how to get only id from struct without loop

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)

This is feed model file:

type Feed struct {
	Model
	Status     string      `json:"status"`
    PublishAt  *time.Time  `json:"publishAt"`
	UserID     string      `json:"userID,omitempty"`
}

This is model base data model using for data entity:

type Model struct {
    ID        string     `json:"id" gorm:"primary_key"`
}

Result:

[
        {
                "id": "d95d4be5-b53c-4c70-aa09",
                "status": "",
                "publishAt": null,
                "userID":""
        },
        {
                "id": "84b2d46f-a24d-4854-b44d",
                "status": "",
                "publishAt": null,
                "userID":""
        }
]

But I want like this:

["d95d4be5-b53c-4c70-aa09","84b2d46f-a24d-4854-b44d"]

答案1

得分: 5

你可以使用pluck

var ids []string
db.Model(&Feed{}).Where("user_id = ?", "admin1").Pluck("id", &ids)
英文:

You can use pluck

var ids []string
db.Model(&Feed{}).Where("user_id = ?", "admin1").Pluck("id", &ids)

huangapple
  • 本文由 发表于 2022年3月19日 12:45:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/71535440.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定