Skip to content

Commit

Permalink
chore: adding query province code in regency
Browse files Browse the repository at this point in the history
  • Loading branch information
Yuefii committed Sep 9, 2024
1 parent eb388d9 commit fa87bbf
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 9 deletions.
26 changes: 20 additions & 6 deletions examples/api-go/handlers/regencies_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ func (handler *Handler) GetRegencies(ctx *gin.Context) {
showAll := ctx.Query("show_all") == "true"
pageStr := ctx.Query("page")
perPageStr := ctx.Query("per_page")
provinceCode := ctx.Query("province_code")

page := 1
perPage := 10
Expand All @@ -34,10 +35,18 @@ func (handler *Handler) GetRegencies(ctx *gin.Context) {

if showAll {

result := handler.db.Find(&regency)
if result.Error != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
return
if provinceCode != "" {
result := handler.db.Preload("Province").Where("province_code = ?", provinceCode).Find(&regency)
if result.Error != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
return
}
} else {
result := handler.db.Preload("Province").Find(&regency)
if result.Error != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
return
}
}
totalItems = int64(len(regency))

Expand All @@ -57,13 +66,18 @@ func (handler *Handler) GetRegencies(ctx *gin.Context) {
return
}

result := handler.db.Model(&models.Regencies{}).Count(&totalItems)
query := handler.db.Model(&models.Regencies{})
if provinceCode != "" {
query = query.Where("province_code = ?", provinceCode)
}

result := query.Count(&totalItems)
if result.Error != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
return
}

result = handler.db.Offset((page - 1) * perPage).Limit(perPage).Find(&regency)
result = query.Preload("Province").Offset((page - 1) * perPage).Limit(perPage).Find(&regency)
if result.Error != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
return
Expand Down
7 changes: 4 additions & 3 deletions examples/api-go/models/regencies.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package models

type Regencies struct {
Code string `gorm:"column:code"`
ProvinceCode string `gorm:"column:province_code"`
Name string `gorm:"column:name"`
Code string `gorm:"column:code"`
ProvinceCode string `gorm:"column:province_code"`
Name string `gorm:"column:name"`
Province Provinces `gorm:"foreignkey:ProvinceCode;references:Code"`
}

0 comments on commit fa87bbf

Please sign in to comment.