I am trying to bind the array type and put the values contained in the array one by one
i tried for loop but have json return, so only 1 is stored
like this
log_id|tag_id|
------ ------
1 | 1|
http body
{
"LogId" : 1
"tags" : [1,2,3,4,5,6,7,8,9]
}
var binder struct {
LogId uuid.UUID `json:"logId"`
TagId []int32 `json:"tags"`
}
json.Unmarshal([]byte(c.Request().Body), &binder)
err := h.UseCases.CreateReviewLogUseCase.Use(c.Ctx(),
database.ReviewLogDenyTag{
LogID: binder.LogId,
TagID: binder.TagId,
})
return c.JSON(http.StatusCreated, map[string]string{
"message": "success",
})
how to execute like this
log_id|tag_id|
------ ------
1 | 1|
1 | 2|
1 | 3|
1 | 4|
1 | 5|
1 | 6|
1 | 7|
1 | 8|
1 | 9|
thank you
CodePudding user response:
It looks like your issue is that you're not actually iterating over your list of tags. Every programming language out there has a syntax allowing you to do this, usually called a for-loop. In Go, for loops have a couple of valid syntaxes: for {starting}; {ending}; {update} {}
like in C, or for {index}, {value} := range {collection} {}
. The first syntax, although usable, isn't the best for your use case so we'll go with the second. Applying it gives:
for _, tag := range binder.TagId {
err := h.UseCases.CreateReviewLogUseCase.Use(c.Ctx(),
database.ReviewLogDenyTag{
LogID: binder.LogId,
TagID: tag,
})
}
What this is doing is iterating over every entry in binder.TagId
, which is a slice of integers, and extracting the value and index of each item. In this example we discard the index as it isn't needed and use the value directly.