func _update(values ...interface{})(string, []interface{}) { tableName := values[0] m := values[1].(map[string]interface{}) var keys []string var vars []interface{} for k, v := range m { keys = append(keys, k+" = ?") vars = append(vars, v) } return fmt.Sprintf("UPDATE %s SET %s", tableName, strings.Join(keys, ", ")), vars }
// support map[string]interface{} // also support kv list: "Name", "Tom", "Age", 18, .... func(s *Session)Update(kv ...interface{})(int64, error) { m, ok := kv[0].(map[string]interface{}) if !ok { m = make(map[string]interface{}) for i := 0; i < len(kv); i += 2 { m[kv[i].(string)] = kv[i+1] } } s.clause.Set(clause.UPDATE, s.RefTable().Name, m) sql, vars := s.clause.Build(clause.UPDATE, clause.WHERE) result, err := s.Raw(sql, vars...).Exec() if err != nil { return0, err } return result.RowsAffected() }
// Limit adds limit condition to clause func(s *Session)Limit(num int) *Session { s.clause.Set(clause.LIMIT, num) return s }
// Where adds limit condition to clause func(s *Session)Where(desc string, args ...interface{}) *Session { var vars []interface{} s.clause.Set(clause.WHERE, append(append(vars, desc), args...)...) return s }
// OrderBy adds order by condition to clause func(s *Session)OrderBy(desc string) *Session { s.clause.Set(clause.ORDERBY, desc) return s }
3 First 只返回一条记录
很多时候,我们期望 SQL 语句只返回一条记录,比如根据某个童鞋的学号查询他的信息,返回结果有且只有一条。结合链式调用,我们可以非常容易地实现 First 方法。