普通查询:
func (c *BackupPlanNewController) ModifyBackupObjects(){
fmt.Println("In the ModifyBackupObjects")
backupPlanId := c.Ctx.Input.Param(":backupPlanId")
backupPlan := models.BackupPlan{Id: backupPlanId}
o := orm.NewOrm()
if err := o.Read(&backupPlan); err != nil {
c.RenderFailResponse(400, fmt.Sprintf("对应备份策略不存在: %s", err.Error()))
return
}
c.RenderSuccessResponse(200, "Good")
return
}
外键关联查询:
// @router / [get]
func (c *AgentNewController) GetAllAgents() {
o := orm.NewOrm()
var maps []orm.Params
qs := o.QueryTable(new(models.BackupFile))
// 通过双下划线做到外键关联查询
_, err := qs.Values(&maps, "Attr","Attr__BinlogStartTime")
for _, m := range maps {
fmt.Println(common.ParseStringInterface(m["Id"]))
}
if err != nil {
c.RenderSuccessResponse(200, err.Error())
}
c.RenderSuccessResponse(200, "Good")
return
}
func (c *BackupFileNewController) DescribeLogicalBackups(){
fmt.Println("In the DescribeLogicalBackups")
backupPlanId := c.Ctx.Input.Param(":backupPlanId")
fmt.Println(backupPlanId)
o := orm.NewOrm()
qs := o.QueryTable(new(models.BackupPlan))
var backupPlan models.BackupPlan
// 通过 qs.RelatedSel("modelName")做到外键关联查询
err := qs.Filter("Id", backupPlanId).RelatedSel("DataSource").One(&backupPlan)
if err != nil{
c.RenderFailResponse(400, err.Error())
return
}
c.RenderSuccessResponse(200, "Good")
return
}
ORM 对时间列的处理:
type BackupPlan struct {
.......
UpdateTime time.Time `orm:"column(update_time);auto_now;type(datetime)"`
.......
}
o1 := orm.NewOrm()
now := time.Now()
fmt.Printf("now = %s\n", now)
// Case1: 这种写法不会更新时间列:
// 对应的 SQL: [UPDATE `backup_plan` T0 SET T0.`stat` = ? WHERE T0.`uid` = ? ] - `111`, `ce3a491e28db11ecb7cdfa163e771f31`
_, _ = o1.QueryTable("backup_plan").Filter("Id", "ce3a491e28db11ecb7cdfa163e771f31").Update(orm.Params{"stat": "111"})
//Case2:明确指定时间列,则
//对应的 SQL: [UPDATE `backup_plan` T0 SET T0.`stat` = ?, T0.`update_time` = ? WHERE T0.`uid` = ? ] - `222`, `2022-01-20 14:34:44.904120919 +0800 CST m=+2.513680714`, `ce3a491e28db11ecb7cdfa163e771f31`
_, _ = o1.QueryTable("backup_plan").Filter("Id", "ce3a491e28db11ecb7cdfa163e771f31").Update(orm.Params{"stat": "222","update_time":now})
backupPlan1 := models.BackupPlan{Id: "ce3a491e28db11ecb7cdfa163e771f31"}
//Case3: 这种写法自动更新时间列:
// 对应的SQL: [UPDATE `backup_plan` SET `stat` = ?, `update_time` = ? WHERE `uid` = ?] - `333`, `2022-01-20 14:34:44.914204963 +0800 CST m=+2.523764754`, `ce3a491e28db11ecb7cdfa163e771f31`
_ = o1.Read(&backupPlan1)
backupPlan1.Stat = "333"
o1.Update(&backupPlan1, "Stat")
c.RenderFailResponse(200, "abc")
POST 请求:
postman 中 post 请求 body
{
"name":"robert"
}
在视图函数中反序列化
case1:
type InitBackupPlanInput struct {
Name string `json:"name"`
}
case2:
type InitBackupPlanInput struct {
Name *string `json:"name"`
}
这两种写法都是可以的即 Name 的类型是可以 string 也可以是 * string
var param InitBackupPlanInput
if err := json.Unmarshal(c.Ctx.Input.RequestBody, ¶m); err != nil {
c.RenderFailResponse(400, err.Error())
return
}
fmt.Println(param.Name)
fmt.Println(*param.Name)