Fix JoinTableHandler JoinWith

This commit is contained in:
Jinzhu 2015-03-19 16:42:13 +08:00
parent fa753969b1
commit 36efd0a561
2 changed files with 6 additions and 4 deletions

View File

@ -143,7 +143,7 @@ func TestManyToMany(t *testing.T) {
// Query // Query
var newLanguages []Language var newLanguages []Language
DB.Model(&user).Related(&newLanguages, "Languages") DB.Debug().Model(&user).Related(&newLanguages, "Languages")
if len(newLanguages) != len([]string{"ZH", "EN"}) { if len(newLanguages) != len([]string{"ZH", "EN"}) {
t.Errorf("Query many to many relations") t.Errorf("Query many to many relations")
} }

View File

@ -128,7 +128,8 @@ func (s JoinTableHandler) JoinWith(db *DB, source interface{}) *DB {
var values []interface{} var values []interface{}
if s.Source.ModelType == modelType { if s.Source.ModelType == modelType {
for _, foreignKey := range s.Destination.ForeignKeys { for _, foreignKey := range s.Destination.ForeignKeys {
joinConditions = append(joinConditions, fmt.Sprintf("%v.%v = %v.%v", quotedTable, scope.Quote(foreignKey.DBName), scope.QuotedTableName(), scope.Quote(foreignKey.AssociationDBName))) destinationTableName := scope.New(reflect.New(s.Destination.ModelType).Interface()).QuotedTableName()
joinConditions = append(joinConditions, fmt.Sprintf("%v.%v = %v.%v", quotedTable, scope.Quote(foreignKey.DBName), destinationTableName, scope.Quote(foreignKey.AssociationDBName)))
} }
for _, foreignKey := range s.Source.ForeignKeys { for _, foreignKey := range s.Source.ForeignKeys {
@ -137,7 +138,8 @@ func (s JoinTableHandler) JoinWith(db *DB, source interface{}) *DB {
} }
} else if s.Destination.ModelType == modelType { } else if s.Destination.ModelType == modelType {
for _, foreignKey := range s.Source.ForeignKeys { for _, foreignKey := range s.Source.ForeignKeys {
joinConditions = append(joinConditions, fmt.Sprintf("%v.%v = %v.%v", quotedTable, scope.Quote(foreignKey.DBName), scope.QuotedTableName(), scope.Quote(foreignKey.AssociationDBName))) sourceTableName := scope.New(reflect.New(s.Source.ModelType).Interface()).QuotedTableName()
joinConditions = append(joinConditions, fmt.Sprintf("%v.%v = %v.%v", quotedTable, scope.Quote(foreignKey.DBName), sourceTableName, scope.Quote(foreignKey.AssociationDBName)))
} }
for _, foreignKey := range s.Destination.ForeignKeys { for _, foreignKey := range s.Destination.ForeignKeys {
@ -146,6 +148,6 @@ func (s JoinTableHandler) JoinWith(db *DB, source interface{}) *DB {
} }
} }
return db.Joins(fmt.Sprintf("INNER JOIN %v ON %v", strings.Join(joinConditions, " AND "))). return db.Joins(fmt.Sprintf("INNER JOIN %v ON %v", quotedTable, strings.Join(joinConditions, " AND "))).
Where(strings.Join(queryConditions, " AND "), values...) Where(strings.Join(queryConditions, " AND "), values...)
} }