From 3cd81ff646090931556cf5590c41ac5d5746357c Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 3 Sep 2020 18:42:32 +0800 Subject: [PATCH] Fix query with specified table and conditions, close #3382 --- statement.go | 8 ++++---- tests/query_test.go | 9 ++++++++- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/statement.go b/statement.go index d72a086f..e16cf0ff 100644 --- a/statement.go +++ b/statement.go @@ -317,9 +317,9 @@ func (stmt *Statement) BuildCondition(query interface{}, args ...interface{}) (c if field.Readable { if v, isZero := field.ValueOf(reflectValue); !isZero { 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 != "" { - 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 v, isZero := field.ValueOf(reflectValue.Index(i)); !isZero { 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 != "" { - 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}) } } } diff --git a/tests/query_test.go b/tests/query_test.go index 6bb68cd3..795186da 100644 --- a/tests/query_test.go +++ b/tests/query_test.go @@ -202,7 +202,6 @@ func TestFind(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) } } + +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()) + } +}