mirror of https://github.com/go-gorm/gorm.git
Fix query with Joins
This commit is contained in:
parent
4da2c28d4d
commit
eeb9ba2250
20
main_test.go
20
main_test.go
|
@ -425,21 +425,35 @@ func TestGroup(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestJoins(t *testing.T) {
|
||||
var user = User{
|
||||
Name: "joins",
|
||||
Emails: []Email{{Email: "join1@example.com"}, {Email: "join2@example.com"}},
|
||||
}
|
||||
DB.Save(&user)
|
||||
|
||||
var result User
|
||||
DB.Joins("left join emails on emails.user_id = users.id").Where("name = ?", "joins").First(&result)
|
||||
if result.Name != "joins" || result.Id != user.Id {
|
||||
t.Errorf("Should find all two emails with Join")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJoinsWithSelect(t *testing.T) {
|
||||
type result struct {
|
||||
Name string
|
||||
Email string
|
||||
}
|
||||
|
||||
user := User{
|
||||
Name: "joins",
|
||||
Name: "joins_with_select",
|
||||
Emails: []Email{{Email: "join1@example.com"}, {Email: "join2@example.com"}},
|
||||
}
|
||||
DB.Save(&user)
|
||||
|
||||
var results []result
|
||||
DB.Table("users").Select("name, email").Joins("left join emails on emails.user_id = users.id").Where("name = ?", "joins").Scan(&results)
|
||||
DB.Table("users").Select("name, email").Joins("left join emails on emails.user_id = users.id").Where("name = ?", "joins_with_select").Scan(&results)
|
||||
if len(results) != 2 || results[0].Email != "join1@example.com" || results[1].Email != "join2@example.com" {
|
||||
t.Errorf("Should find all two emails with Join")
|
||||
t.Errorf("Should find all two emails with Join select")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -209,7 +209,7 @@ func (scope *Scope) handleHasManyToManyPreload(field *Field, conditions []interf
|
|||
sourceKeys = append(sourceKeys, key.DBName)
|
||||
}
|
||||
|
||||
db := scope.NewDB().Table(scope.New(reflect.New(destType).Interface()).TableName())
|
||||
db := scope.NewDB().Table(scope.New(reflect.New(destType).Interface()).TableName()).Select("*")
|
||||
preloadJoinDB := joinTableHandler.JoinWith(joinTableHandler, db, scope.Value)
|
||||
if len(conditions) > 0 {
|
||||
preloadJoinDB = preloadJoinDB.Where(conditions[0], conditions[1:]...)
|
||||
|
|
|
@ -213,6 +213,9 @@ var hasCountRegexp = regexp.MustCompile(`(?i)count(.+)`)
|
|||
|
||||
func (scope *Scope) selectSql() string {
|
||||
if len(scope.Search.selects) == 0 {
|
||||
if scope.Search.joins != "" {
|
||||
return fmt.Sprintf("%v.*", scope.QuotedTableName())
|
||||
}
|
||||
return "*"
|
||||
}
|
||||
sql := scope.buildSelectQuery(scope.Search.selects)
|
||||
|
|
Loading…
Reference in New Issue