Home > Software engineering >  How can I query and return only id array by GORM?
How can I query and return only id array by GORM?

Time:03-19

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"]

CodePudding user response:

You can use pluck

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