diff --git a/main_test.go b/main_test.go index e9bffd0f..8ac015c8 100644 --- a/main_test.go +++ b/main_test.go @@ -544,7 +544,7 @@ func TestJoinsWithSelect(t *testing.T) { 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_with_select").Scan(&results) + DB.Table("users").Select("name, emails.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 select") } diff --git a/migration_test.go b/migration_test.go index 81fe4fd3..38e5c1c2 100644 --- a/migration_test.go +++ b/migration_test.go @@ -16,7 +16,8 @@ type User struct { Id int64 Age int64 UserNum Num - Name string `sql:"size:255"` + Name string `sql:"size:255"` + Email string Birthday time.Time // Time CreatedAt time.Time // CreatedAt: Time of record is created, will be insert automatically UpdatedAt time.Time // UpdatedAt: Time of record is updated, will be updated automatically diff --git a/query_test.go b/query_test.go index b376dc82..7dc3d91b 100644 --- a/query_test.go +++ b/query_test.go @@ -31,9 +31,14 @@ func TestFirstAndLast(t *testing.T) { t.Errorf("Find first record as slice") } - if DB.Joins("left join emails on emails.user_id = users.id").First(&User{}).Error != nil { + var user User + if DB.Joins("left join emails on emails.user_id = users.id").First(&user).Error != nil { t.Errorf("Should not raise any error when order with Join table") } + + if user.Email != "" { + t.Errorf("User's Email should be blank as no one set it") + } } func TestFirstAndLastWithNoStdPrimaryKey(t *testing.T) { diff --git a/scope.go b/scope.go index 9a8acbd3..45e197c4 100644 --- a/scope.go +++ b/scope.go @@ -462,10 +462,10 @@ func (scope *Scope) scan(rows *sql.Rows, columns []string, fields []*Field) { selectFields = fields if idx, ok := selectedColumnsMap[column]; ok { - selectFields = selectFields[idx:] + selectFields = selectFields[idx+1:] } - for _, field := range selectFields { + for fieldIndex, field := range selectFields { if field.DBName == column { if field.Field.Kind() == reflect.Ptr { values[index] = field.Field.Addr().Interface() @@ -475,6 +475,8 @@ func (scope *Scope) scan(rows *sql.Rows, columns []string, fields []*Field) { values[index] = reflectValue.Interface() resetFields[field] = index } + + selectedColumnsMap[column] = fieldIndex break } }