## **查询数据** * 代码存放位置 ![](https://img.kancloud.cn/35/2e/352e36dd3242c3d6466572507a52e980_490x306.png) ### 模型 ~~~ package models import ( "github.com/gin-gonic/gin" "learn_gin/db" ) // Staff 结构体封装字段 type Staff struct { Id int `json:"id"` Status int `json:"status"` InfoId int `json:"info_id"` Nickname string `json:"nickname"` Account string `json:"account"` Password string `json:"password"` CreatedAt string `json:"created_at"` UpdatedAt string `json:"updated_at"` } // TableName 该模型链接的数据表名 func (Staff) TableName() string { return "staff" } // Condition 搜索条件 func (Staff)Condition(ctx *gin.Context) string { where := "1=1" nickname := ctx.DefaultQuery("nickname","") account:= ctx.DefaultQuery("account","") status:= ctx.DefaultQuery("status","") if status != ""{ where += " AND `status` = " + status } if nickname != ""{ where += " AND `nickname` like " + status + "%" } if account != ""{ where += " AND `account` like " + account + "%" } return where } // List 查询列表 func(Staff) List(condition string) []Staff { var result []Staff //result := make([]models.Staff, 0) db.DB.Table("staff").Where(condition).Find(&result) return result } ~~~ ### 控制器 ~~~ package api import ( "fmt" "github.com/gin-gonic/gin" "learn_gin/db" "learn_gin/models" ) type StaffController struct { BaseController } func (staff StaffController) List(ctx *gin.Context) { condition := models.Staff{}.Condition(ctx) result := models.Staff{}.List(condition) ctx.JSON(200,gin.H{ "result":result, }) } ~~~