【发布时间】:2021-12-24 17:29:21
【问题描述】:
Struct & Map Conditions 的 Gorm 文档提供了以下 sn-p 用于查询具有主键切片的表
// Slice of primary keys
db.Where([]int64{20, 21, 22}).Find(&users)
// SELECT * FROM users WHERE id IN (20, 21, 22);
但是,如果切片为空,则返回所有记录。查看source code 的Find 函数,我可以看到只有在len(conds) > 0 时才添加条件
// Find find records that match given conditions
func (db *DB) Find(dest interface{}, conds ...interface{}) (tx *DB) {
tx = db.getInstance()
if len(conds) > 0 {
if exprs := tx.Statement.BuildCondition(conds[0], conds[1:]...); len(exprs) > 0 {
tx.Statement.AddClause(clause.Where{Exprs: exprs})
}
}
tx.Statement.Dest = dest
return tx.callbacks.Query().Execute(tx)
}
这与我的 SQLite 命令行返回的相反。如果条件为空,则不返回任何记录(因为它们都有主键)
-- no records returned
SELECT * FROM my_table WHERE id IN ();
问题
- 有没有办法使用 Gorm 查询主键切片,如果切片为空,则不返回任何记录?
【问题讨论】:
标签: go-gorm