Skip to content

Commit

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

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

if showAll {

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

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

result := handler.db.Model(&models.Villages{}).Count(&totalItems)
query := handler.db.Model(&models.Villages{})
if districtCode != "" {
query = query.Where("district_code = ?", districtCode)
}

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

type Villages struct {
Code string `gorm:"column:code"`
VillageCode string `gorm:"column:village_code"`
Name string `gorm:"column:name"`
Code string `gorm:"column:code"`
DistrictCode string `gorm:"column:district_code"`
Name string `gorm:"column:name"`
District Districts `gorm:"foreignkey:DistrictCode;references:Code"`
}

0 comments on commit 97b3fc7

Please sign in to comment.