Allow Omit with Query, close #3165

This commit is contained in:
Jinzhu 2020-07-19 21:48:58 +08:00
parent 90183fadde
commit a0477f94dd
2 changed files with 23 additions and 0 deletions

View File

@ -64,6 +64,14 @@ func BuildQuerySQL(db *gorm.DB) {
clauseSelect.Columns[idx] = clause.Column{Name: name, Raw: true} clauseSelect.Columns[idx] = clause.Column{Name: name, Raw: true}
} }
} }
} else if db.Statement.Schema != nil && len(db.Statement.Omits) > 0 {
selectColumns, _ := db.Statement.SelectAndOmitColumns(false, false)
clauseSelect.Columns = make([]clause.Column, 0, len(db.Statement.Schema.DBNames))
for _, dbName := range db.Statement.Schema.DBNames {
if v, ok := selectColumns[dbName]; (ok && v) || !ok {
clauseSelect.Columns = append(clauseSelect.Columns, clause.Column{Name: dbName})
}
}
} else if db.Statement.Schema != nil && db.Statement.ReflectValue.IsValid() { } else if db.Statement.Schema != nil && db.Statement.ReflectValue.IsValid() {
smallerStruct := false smallerStruct := false
switch db.Statement.ReflectValue.Kind() { switch db.Statement.ReflectValue.Kind() {

View File

@ -330,6 +330,21 @@ func TestSelect(t *testing.T) {
} }
} }
func TestOmit(t *testing.T) {
user := User{Name: "OmitUser1", Age: 20}
DB.Save(&user)
var result User
DB.Where("name = ?", user.Name).Omit("name").Find(&result)
if result.ID == 0 {
t.Errorf("Should not have ID because only selected name, %+v", result.ID)
}
if result.Name != "" || result.Age != 20 {
t.Errorf("User Name should be omitted, got %v, Age should be ok, got %v", result.Name, result.Age)
}
}
func TestPluckWithSelect(t *testing.T) { func TestPluckWithSelect(t *testing.T) {
users := []User{ users := []User{
{Name: "pluck_with_select_1", Age: 25}, {Name: "pluck_with_select_1", Age: 25},