Skip to content

Commit

Permalink
chore: adding query regency code in districts
Browse files Browse the repository at this point in the history
  • Loading branch information
Yuefii committed Sep 9, 2024
1 parent fa87bbf commit b2e16f7
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/districts_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ func (handler *Handler) GetDistricts(ctx *gin.Context) {
showAll := ctx.Query("show_all") == "true"
pageStr := ctx.Query("page")
perPageStr := ctx.Query("per_page")
regencyCode := ctx.Query("regency_code")

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

if showAll {

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

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

result := handler.db.Model(&models.Districts{}).Count(&totalItems)
query := handler.db.Model(&models.Districts{})
if regencyCode != "" {
query = query.Where("regency_code = ?", regencyCode)
}

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(&district)
result = query.Preload("Regency").Offset((page - 1) * perPage).Limit(perPage).Find(&district)
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/districts.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package models

type Districts struct {
Code string `gorm:"column:code"`
RegencyCode string `gorm:"column:regency_code"`
Name string `gorm:"column:name"`
Code string `gorm:"column:code"`
RegencyCode string `gorm:"column:regency_code"`
Name string `gorm:"column:name"`
Regency Regencies `gorm:"foreignkey:RegencyCode;references:Code"`
}

0 comments on commit b2e16f7

Please sign in to comment.