From 045d5f853838b9800acdb8ae204969ba3d93e00a Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 13 Aug 2020 12:18:36 +0800 Subject: [PATCH] Fix count with join and no model, close #3255 --- callbacks/query.go | 2 +- tests/count_test.go | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/callbacks/query.go b/callbacks/query.go index be829fbc..5ae1e904 100644 --- a/callbacks/query.go +++ b/callbacks/query.go @@ -96,7 +96,7 @@ func BuildQuerySQL(db *gorm.DB) { // inline joins if len(db.Statement.Joins) != 0 { - if len(db.Statement.Selects) == 0 { + if len(db.Statement.Selects) == 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/count_test.go b/tests/count_test.go index 05661ae8..216fa3a1 100644 --- a/tests/count_test.go +++ b/tests/count_test.go @@ -67,4 +67,9 @@ func TestCount(t *testing.T) { if !regexp.MustCompile(`SELECT COUNT\(DISTINCT\(.name.\)\) FROM .*users.*`).MatchString(result.Statement.SQL.String()) { t.Fatalf("Build count with select, but got %v", result.Statement.SQL.String()) } + + var count4 int64 + if err := DB.Debug().Table("users").Joins("LEFT JOIN companies on companies.name = users.name").Where("users.name = ?", user1.Name).Count(&count4).Error; err != nil || count4 != 1 { + t.Errorf("count with join, got error: %v, count %v", err, count) + } }