Select specify fields that you want when querying, creating, updating Use Select when you only want a subset of the fields. By default, GORM will select all fields. Select accepts both string arguments and arrays. // Select name and age of user using multiple arguments db.Select("name", "age").F
(query interface{}, args ...interface{})
| 110 | // // Select name and age of user using an array |
| 111 | // db.Select([]string{"name", "age"}).Find(&users) |
| 112 | func (db *DB) Select(query interface{}, args ...interface{}) (tx *DB) { |
| 113 | tx = db.getInstance() |
| 114 | |
| 115 | switch v := query.(type) { |
| 116 | case []string: |
| 117 | tx.Statement.Selects = v |
| 118 | |
| 119 | for _, arg := range args { |
| 120 | switch arg := arg.(type) { |
| 121 | case string: |
| 122 | tx.Statement.Selects = append(tx.Statement.Selects, arg) |
| 123 | case []string: |
| 124 | tx.Statement.Selects = append(tx.Statement.Selects, arg...) |
| 125 | default: |
| 126 | tx.AddError(fmt.Errorf("unsupported select args %v %v", query, args)) |
| 127 | return |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | if clause, ok := tx.Statement.Clauses["SELECT"]; ok { |
| 132 | clause.Expression = nil |
| 133 | tx.Statement.Clauses["SELECT"] = clause |
| 134 | } |
| 135 | case string: |
| 136 | if strings.Count(v, "?") >= len(args) && len(args) > 0 { |
| 137 | tx.Statement.AddClause(clause.Select{ |
| 138 | Distinct: db.Statement.Distinct, |
| 139 | Expression: clause.Expr{SQL: v, Vars: args}, |
| 140 | }) |
| 141 | } else if strings.Count(v, "@") > 0 && len(args) > 0 { |
| 142 | tx.Statement.AddClause(clause.Select{ |
| 143 | Distinct: db.Statement.Distinct, |
| 144 | Expression: clause.NamedExpr{SQL: v, Vars: args}, |
| 145 | }) |
| 146 | } else { |
| 147 | tx.Statement.Selects = []string{v} |
| 148 | |
| 149 | for _, arg := range args { |
| 150 | switch arg := arg.(type) { |
| 151 | case string: |
| 152 | tx.Statement.Selects = append(tx.Statement.Selects, arg) |
| 153 | case []string: |
| 154 | tx.Statement.Selects = append(tx.Statement.Selects, arg...) |
| 155 | default: |
| 156 | tx.Statement.AddClause(clause.Select{ |
| 157 | Distinct: db.Statement.Distinct, |
| 158 | Expression: clause.Expr{SQL: v, Vars: args}, |
| 159 | }) |
| 160 | return |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | if clause, ok := tx.Statement.Clauses["SELECT"]; ok { |
| 165 | clause.Expression = nil |
| 166 | tx.Statement.Clauses["SELECT"] = clause |
| 167 | } |
| 168 | } |
| 169 | default: |
nothing calls this directly
no test coverage detected