Beego ORM操作 Filter 报错 Condition.And args cannot empty 解决方法

问题报错

报错提示

<Condition.And> args cannot empty

Model模型

type User struct {
	Id         int
	Username   string    // 用户名
	Password   string    // 密码
	CreateTime time.Time `orm:"auto_now_add;type(datetime)"` // 创建时间
}

错误的Filter语句

//通过用户名来读取数据库中的密码 - 报错
err != o.QueryTable("user").Filter("username").One(&user, "password")

这个使用方式是错误的,因为我认为Filter的使用方法和Read一样导致的。

Filter的正确使用方法

// 注意在"username"字段后面加入判断条件(默认是等于)
o.QueryTable("user").Filter("username", &user.Username).One(&user, "password")

低级错误应引以为鉴,多看技术文档,多学习

技术文档

Filter 用来过滤查询结果,起到包含条件的作用,多个Filter之间使用AND连接。

qs.Filter("profile__isnull", true).Filter("name", "slene")
// WHERE profile_id IS NULL AND name = 'slene'

源代码

// 添加一个判断条件到 QuerySeter.
func (o querySet) Filter(expr string, args ...interface{}) QuerySeter {
	if o.cond == nil {
		o.cond = NewCondition()
	}
	o.cond = o.cond.And(expr, args...)
	return &o
}

使用expr(判断式)

qs.Filter("id", 1) // WHERE id = 1
qs.Filter("profile__age", 18) // WHERE profile.age = 18
qs.Filter("Profile__Age", 18) // 使用字段名和 Field 名都是允许的
qs.Filter("profile__age", 18) // WHERE profile.age = 18
qs.Filter("profile__age__gt", 18) // WHERE profile.age > 18
qs.Filter("profile__age__gte", 18) // WHERE profile.age >= 18
qs.Filter("profile__age__in", 18, 20) // WHERE profile.age IN (18, 20)

qs.Filter("profile__age__in", 18, 20).Exclude("profile__lt", 1000)
// WHERE profile.age IN (18, 20) AND NOT profile_id < 1000