【问题标题】:Gorm Go - Query with an empty slice of primary keysGorm Go - 使用空的主键切片进行查询
【发布时间】: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 codeFind 函数,我可以看到只有在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


    【解决方案1】:

    由于主键从1 增加,0 id 可以在空查询中使用。

    ids := []int64{20, 21, 22}
    db.Where(append([]int64{0}, ids...)).Find(&users)
    

    【讨论】:

    猜你喜欢
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 2017-11-02
    • 2020-06-08
    • 1970-01-01
    相关资源
    最近更新 更多