forked from mirror/gorm
Test update from sub query
This commit is contained in:
parent
045d5f8538
commit
ecc946be6e
|
@ -174,11 +174,16 @@ func ConvertToAssignments(stmt *gorm.Statement) (set clause.Set) {
|
|||
sort.Strings(keys)
|
||||
|
||||
for _, k := range keys {
|
||||
kv := value[k]
|
||||
if _, ok := kv.(*gorm.DB); ok {
|
||||
kv = []interface{}{kv}
|
||||
}
|
||||
|
||||
if stmt.Schema != nil {
|
||||
if field := stmt.Schema.LookUpField(k); field != nil {
|
||||
if field.DBName != "" {
|
||||
if v, ok := selectColumns[field.DBName]; (ok && v) || (!ok && !restricted) {
|
||||
set = append(set, clause.Assignment{Column: clause.Column{Name: field.DBName}, Value: value[k]})
|
||||
set = append(set, clause.Assignment{Column: clause.Column{Name: field.DBName}, Value: kv})
|
||||
assignValue(field, value[k])
|
||||
}
|
||||
} else if v, ok := selectColumns[field.Name]; (ok && v) || (!ok && !restricted) {
|
||||
|
@ -189,7 +194,7 @@ func ConvertToAssignments(stmt *gorm.Statement) (set clause.Set) {
|
|||
}
|
||||
|
||||
if v, ok := selectColumns[k]; (ok && v) || (!ok && !restricted) {
|
||||
set = append(set, clause.Assignment{Column: clause.Column{Name: k}, Value: value[k]})
|
||||
set = append(set, clause.Assignment{Column: clause.Column{Name: k}, Value: kv})
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -545,3 +545,21 @@ func TestUpdatesTableWithIgnoredValues(t *testing.T) {
|
|||
t.Errorf("element's ignored field should not be updated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateFromSubQuery(t *testing.T) {
|
||||
user := *GetUser("update_from_sub_query", Config{Company: true})
|
||||
if err := DB.Create(&user).Error; err != nil {
|
||||
t.Errorf("failed to create user, got error: %v", err)
|
||||
}
|
||||
|
||||
if err := DB.Model(&user).Update("name", DB.Model(&Company{}).Select("name").Where("companies.id = users.company_id")).Error; err != nil {
|
||||
t.Errorf("failed to update with sub query, got error %v", err)
|
||||
}
|
||||
|
||||
var result User
|
||||
DB.First(&result, user.ID)
|
||||
|
||||
if result.Name != user.Company.Name {
|
||||
t.Errorf("name should be %v, but got %v", user.Company.Name, result.Name)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue