V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
252748371
V2EX  ›  Go 编程语言

gorm 使用原生 sql 如何不定参数查询?

  •  
  •   252748371 · 2019-09-05 10:40:40 +08:00 · 6331 次点击
    这是一个创建于 1666 天前的主题,其中的信息可能已经有所发展或是发生改变。
    10 条回复    2019-09-07 18:54:59 +08:00
    leon0903
        1
    leon0903  
       2019-09-05 12:11:58 +08:00
    db.Raw("SELECT * FROM kd_online_edit_file WHERE aaa = ? and bbb = ? ", aaa, bbb).Find(&result)
    not4jerk
        2
    not4jerk  
       2019-09-05 13:20:08 +08:00   ❤️ 1
    if columen != "" 模式

    ```go
    func (m SshLogQ) Search(u *User) (list *[]SshLog, total uint, err error) {
    list = &[]SshLog{}
    tx := db.Model(m.SshLog).Preload("User").Preload("Machine")
    if m.ClientIp != "" {
    tx = tx.Where("client_ip like ?", "%"+m.ClientIp+"%")
    }
    if m.FromTime != "" && m.ToTime != "" {
    tx = tx.Where("`created_at` BETWEEN ? AND ?", m.FromTime, m.ToTime)
    }

    if u.IsAdmin() {
    if m.UserId > 0 {
    tx = tx.Where("user_id = ?", m.UserId)
    }
    if m.MachineId > 0 {
    tx = tx.Where("machine_id = ?", m.MachineId)
    }
    } else {
    //非管理员 智能看自己的日志
    //不支持搜索搜索
    tx = tx.Where("`user_id` = ?", u.Id)
    }
    total, err = crudAll(&m.PaginationQ, tx, list)
    return
    }
    ```
    252748371
        3
    252748371  
    OP
       2019-09-05 16:08:55 +08:00
    是这样的
    我不知道前端到底有没有传查询的条件
    若传了查询的条件=>sql 加上"where xxx = xxx "
    https://blog.csdn.net/linux_player_c/article/details/82351934 这里可以参考一下,不过是用 orm 的
    原生的 sql 怎么写
    liuxey
        4
    liuxey  
       2019-09-05 16:18:27 +08:00
    @252748371 #3 gorm 只是帮你拼了 sql,原生就自己 if else 拼 sql 串
    pubby
        5
    pubby  
       2019-09-05 16:22:59 +08:00   ❤️ 2
    用 gorm.Expr

    var wCond = gorm.Expr("1")
    if xx && oo {
    wCond = gorm.Expr("xx=? AND oo=?",xx,oo)
    }
    db.Raw("SELECT * FROM table1 WHERE ?", wCond).Scan(&rows)
    jss
        6
    jss  
       2019-09-05 21:56:44 +08:00 via iPhone
    给你一个思路,where 条件为数组,当一个条件存在写入数组,最后 for db.where
    252748371
        7
    252748371  
    OP
       2019-09-06 11:03:37 +08:00
    @liuxey

    我可以自己拼字符串
    252748371
        8
    252748371  
    OP
       2019-09-06 11:04:34 +08:00
    @liuxey
    我可以自己拼字符串
    但是 sql += " and xxx = " + "xxx"
    252748371
        9
    252748371  
    OP
       2019-09-06 11:05:01 +08:00
    @liuxey
    这样不会 sql 注入吗
    liuxey
        10
    liuxey  
       2019-09-07 18:54:59 +08:00
    @252748371 #9 用绑定参数的 sql 啊。。。 WHERE aaa = ? and bbb = ? 拼这种 不是拼 value
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1122 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 67ms · UTC 22:50 · PVG 06:50 · LAX 15:50 · JFK 18:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.