Fix query with specified table and conditions, close #3382

This commit is contained in:
Jinzhu 2020-09-03 18:42:32 +08:00
parent 78e9c9b748
commit 3cd81ff646
2 changed files with 12 additions and 5 deletions

View File

@ -317,9 +317,9 @@ func (stmt *Statement) BuildCondition(query interface{}, args ...interface{}) (c
if field.Readable { if field.Readable {
if v, isZero := field.ValueOf(reflectValue); !isZero { if v, isZero := field.ValueOf(reflectValue); !isZero {
if field.DBName != "" { if field.DBName != "" {
conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.DBName}, Value: v}) conds = append(conds, clause.Eq{Column: clause.Column{Table: clause.CurrentTable, Name: field.DBName}, Value: v})
} else if field.DataType != "" { } else if field.DataType != "" {
conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.Name}, Value: v}) conds = append(conds, clause.Eq{Column: clause.Column{Table: clause.CurrentTable, Name: field.Name}, Value: v})
} }
} }
} }
@ -330,9 +330,9 @@ func (stmt *Statement) BuildCondition(query interface{}, args ...interface{}) (c
if field.Readable { if field.Readable {
if v, isZero := field.ValueOf(reflectValue.Index(i)); !isZero { if v, isZero := field.ValueOf(reflectValue.Index(i)); !isZero {
if field.DBName != "" { if field.DBName != "" {
conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.DBName}, Value: v}) conds = append(conds, clause.Eq{Column: clause.Column{Table: clause.CurrentTable, Name: field.DBName}, Value: v})
} else if field.DataType != "" { } else if field.DataType != "" {
conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.Name}, Value: v}) conds = append(conds, clause.Eq{Column: clause.Column{Table: clause.CurrentTable, Name: field.Name}, Value: v})
} }
} }
} }

View File

@ -202,7 +202,6 @@ func TestFind(t *testing.T) {
} }
} }
}) })
} }
func TestQueryWithAssociation(t *testing.T) { func TestQueryWithAssociation(t *testing.T) {
@ -800,3 +799,11 @@ func TestScanNullValue(t *testing.T) {
t.Fatalf("failed to query slice data with null age, got error %v", err) t.Fatalf("failed to query slice data with null age, got error %v", err)
} }
} }
func TestQueryWithTableAndConditions(t *testing.T) {
result := DB.Session(&gorm.Session{DryRun: true}).Table("user").Find(&User{}, User{Name: "jinzhu"})
if !regexp.MustCompile(`SELECT \* FROM .user. WHERE .user.\..name. = .+ AND .user.\..deleted_at. IS NULL`).MatchString(result.Statement.SQL.String()) {
t.Errorf("invalid query SQL, got %v", result.Statement.SQL.String())
}
}