From c0bea447b9eb707cfc1712d2d423f43309e247a2 Mon Sep 17 00:00:00 2001 From: li-jin-gou <97824201+li-jin-gou@users.noreply.github.com> Date: Fri, 28 Jan 2022 22:16:42 +0800 Subject: [PATCH] fix: omit not work when use join (#5034) --- callbacks/query.go | 2 +- tests/connection_test.go | 3 +-- tests/joins_test.go | 16 ++++++++++++++++ 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/callbacks/query.go b/callbacks/query.go index c2bbf5f9..49086354 100644 --- a/callbacks/query.go +++ b/callbacks/query.go @@ -100,7 +100,7 @@ func BuildQuerySQL(db *gorm.DB) { } if len(db.Statement.Joins) != 0 || len(joins) != 0 { - if len(db.Statement.Selects) == 0 && db.Statement.Schema != nil { + if len(db.Statement.Selects) == 0 && len(db.Statement.Omits) == 0 && db.Statement.Schema != nil { clauseSelect.Columns = make([]clause.Column, len(db.Statement.Schema.DBNames)) for idx, dbName := range db.Statement.Schema.DBNames { clauseSelect.Columns[idx] = clause.Column{Table: db.Statement.Table, Name: dbName} diff --git a/tests/connection_test.go b/tests/connection_test.go index 92b13dd6..7bc23009 100644 --- a/tests/connection_test.go +++ b/tests/connection_test.go @@ -9,7 +9,7 @@ import ( ) func TestWithSingleConnection(t *testing.T) { - var expectedName = "test" + expectedName := "test" var actualName string setSQL, getSQL := getSetSQL(DB.Dialector.Name()) @@ -27,7 +27,6 @@ func TestWithSingleConnection(t *testing.T) { } return nil }) - if err != nil { t.Errorf(fmt.Sprintf("WithSingleConnection should work, but got err %v", err)) } diff --git a/tests/joins_test.go b/tests/joins_test.go index e276a74a..4c9cffae 100644 --- a/tests/joins_test.go +++ b/tests/joins_test.go @@ -158,6 +158,22 @@ func TestJoinsWithSelect(t *testing.T) { } } +func TestJoinWithOmit(t *testing.T) { + user := *GetUser("joins_with_omit", Config{Pets: 2}) + DB.Save(&user) + + results := make([]*User, 0) + + if err := DB.Table("users").Omit("name").Where("users.name = ?", "joins_with_omit").Joins("left join pets on pets.user_id = users.id").Find(&results).Error; err != nil { + return + } + + if len(results) != 2 || results[0].Name != "" || results[1].Name != "" { + t.Errorf("Should find all two pets with Join omit and should not find user's name, got %+v", results) + return + } +} + func TestJoinCount(t *testing.T) { companyA := Company{Name: "A"} companyB := Company{Name: "B"}