定义实体对象
type Project struct {
ID int `gorm:"primaryKey" json:"id"`
ProjectName string `gorm:"project_name" json:"project_name"`
Status int `gorm:"status" json:"status"`
DistrictIDs *pq.Int64Array `gorm:"column:district_ids;type:integer[]" json:"district_ids"`
CreatedBy string `gorm:"column:created_by" json:"created_by"`
CreatedTime *types.HQDateTime `gorm:"column:created_time" json:"created_time"`
Year string `gorm:"column:year" json:"year"`
}
func (p *Project) TableName() string {
return "project"
}
定义传输参数 url
http://localhost:3025/api/project?districts=1&districts=2
golang 接入参数
if districts, ok := ctx.GetQueryArray("districts"); ok {
array := convertStringArrayToIntArray(districts)
var conditions []string
for _, num := range array {
conditions = append(conditions, fmt.Sprintf("%d", num))
}
whereClause := fmt.Sprintf("district_ids && ARRAY[%s]::integer[]", strings.Join(conditions, ","))
err := db.Raw("SELECT * FROM project WHERE " + whereClause)
}
转化string数组到int数组
func convertStringArrayToIntArray(inputs []string) []int {
var intArray []int
for _, str := range inputs {
num, err := strconv.Atoi(str)
if err != nil {
fmt.Printf("Error converting string to int: %v\n", err)
continue
}
intArray = append(intArray, num)
}
return intArray
}
按照上述方式可以实现字段为数组,传入为数组查询的条件