讨论数量:
按:链式调用《GORM 中文文档》 的‘方法链和协程安全’
func (glc GuestLossController) Count(c *gin.Context) {
var (
pendding int64
success int64
faild int64
)
model := database.DB.Model(guest_loss.GuestLoss{})
//列表显示权限判断
curuser := auth.CurrentUser(c)
if curuser.CheckRole() == 1 {
model.Joins("inner join user on user.id = guest_loss.option_id").Where("user.branch_id = ?", curuser.BranchId)
} else if curuser.CheckRole() == 3 {
model.Where("guest_loss.option_id=?", curuser.ID)
}
if c.Query("begin_at") != "" {
model.Where("guest_loss.created_at > ?", c.Query("begin_at"))
}
if c.Query("end_at") != "" {
model.Where("guest_loss.created_at <= ?", c.Query("end_at"))
}
if c.Query("phone") != "" {
model.Joins("inner join guest on guest.id = guest_loss.guest_id").Where("guest.phone like ?", "%"+c.Query("phone")+"%")
}
ctx1, _ := context.WithTimeout(context.Background(), time.Second)
ctx2, _ := context.WithTimeout(context.Background(), time.Second)
model.WithContext(ctx1).Scopes(guest_loss.Status(0)).Count(&pendding)
model.WithContext(ctx2).Scopes(guest_loss.Status(1)).Count(&success)
model.Scopes(guest_loss.Status(2)).Count(&faild)
response.JSON(c, gin.H{
"pendding": pendding,
"success": success,
"faild": faild,
})
}
方式二:
func (glc GuestLossController) countBase(c *gin.Context) *gorm.DB {
model := database.DB.Model(guest_loss.GuestLoss{})
//列表显示权限判断
curuser := auth.CurrentUser(c)
if curuser.CheckRole() == 1 {
model.Joins("inner join user on user.id = guest_loss.option_id").Where("user.branch_id = ?", curuser.BranchId)
} else if curuser.CheckRole() == 3 {
model.Where("guest_loss.option_id=?", curuser.ID)
}
if c.Query("begin_at") != "" {
model.Where("guest_loss.created_at > ?", c.Query("begin_at"))
}
if c.Query("end_at") != "" {
model.Where("guest_loss.created_at <= ?", c.Query("end_at"))
}
if c.Query("phone") != "" {
model.Joins("inner join guest on guest.id = guest_loss.guest_id").Where("guest.phone like ?", "%"+c.Query("phone")+"%")
}
return model
}
func (glc GuestLossController) Count(c *gin.Context) {
var (
pendding int64
success int64
faild int64
)
glc.countBase().Scopes(guest_loss.Status(0)).Count(&pendding)
glc.countBase().Scopes(guest_loss.Status(1)).Count(&success)
glc.countBase().Scopes(guest_loss.Status(2)).Count(&faild)
response.JSON(c, gin.H{
"pendding": pendding,
"success": success,
"faild": faild,
})
}
方式二: