diff --git a/field/expr.go b/field/expr.go index 1dada9ef..3ab94955 100644 --- a/field/expr.go +++ b/field/expr.go @@ -57,6 +57,12 @@ var ( // WithAll build column with table and alias WithAll BuildOpt = func(col clause.Column) interface{} { return col } + + // WithoutQuote + WithoutQuote BuildOpt = func(col clause.Column) interface{} { + col.Raw = true + return col + } ) func (e expr) BuildColumn(stmt *gorm.Statement, opts ...BuildOpt) sql { @@ -64,6 +70,9 @@ func (e expr) BuildColumn(stmt *gorm.Statement, opts ...BuildOpt) sql { for _, opt := range opts { col = opt(e.col) } + if col, ok := col.(clause.Column); ok && col.Raw { + return sql(col.Table + "." + col.Name) + } return sql(stmt.Quote(col)) } diff --git a/field/external_test.go b/field/external_test.go index bc999a33..928d0952 100644 --- a/field/external_test.go +++ b/field/external_test.go @@ -329,6 +329,24 @@ func TestExpr_Build(t *testing.T) { } } +func TestExpr_BuildColumn(t *testing.T) { + stmt := field.GetStatement() + id := field.NewUint("user", "id") + expectColumnStr := "`id`" + expectColumnStrWithTable := "`user`.`id`" + expectColumnStrWithoutQuote := "user.id" + + if colStr := id.BuildColumn(stmt).String(); colStr != expectColumnStr { + t.Errorf("id.BuildColumn(stmt).String() got: %q, except: %q", colStr, expectColumnStr) + } + if colStr := id.BuildColumn(stmt, field.WithTable).String(); colStr != expectColumnStrWithTable { + t.Errorf("id.BuildColumn(stmt, field.WithTable).String() got: %q, except: %q", colStr, expectColumnStrWithTable) + } + if colStr := id.BuildColumn(stmt, field.WithoutQuote).String(); colStr != expectColumnStrWithoutQuote { + t.Errorf("id.BuildColumn(stmt, field.WithoutQuote).String() got: %q, except: %q", colStr, expectColumnStrWithoutQuote) + } +} + func BenchmarkExpr_Count(b *testing.B) { id := field.NewUint("", "id") for i := 0; i < b.N; i++ {