| 1 |
package tests_test |
| 2 |
|
| 3 |
import ( |
| 4 |
"testing" |
| 5 |
|
| 6 |
"gorm.io/gorm" |
| 7 |
) |
| 8 |
|
| 9 |
type Man struct { |
| 10 |
ID int |
| 11 |
Age int |
| 12 |
Name string |
| 13 |
Detail string |
| 14 |
} |
| 15 |
|
| 16 |
// Panic-safe BeforeUpdate hook that checks for Changed("age") |
| 17 |
func (m *Man) BeforeUpdate(tx *gorm.DB) (err error) { |
| 18 |
if !tx.Statement.Changed("age") { |
| 19 |
return nil |
| 20 |
} |
| 21 |
return nil |
| 22 |
} |
| 23 |
|
| 24 |
func TestSubModel(t *testing.T) { |
| 25 |
man := Man{Age: 18, Name: "random-name"} |
| 26 |
if err := DB.Create(&man).Error; err != nil { |
| 27 |
t.Fatalf("unexpected error: %v", err) |
| 28 |
} |
| 29 |
|
| 30 |
if err := DB.Model(&man).Where("id = ?", man.ID).Updates(struct { |
| 31 |
Age int |
| 32 |
}{Age: 20}).Error; err != nil { |
| 33 |
t.Fatalf("unexpected error: %v", err) |
| 34 |
} |
| 35 |
|
| 36 |
var result = struct { |
| 37 |
ID int |
| 38 |
Age int |
| 39 |
}{} |
| 40 |
if err := DB.Model(&man).Where("id = ?", man.ID).Find(&result).Error; err != nil { |
| 41 |
t.Fatalf("unexpected error: %v", err) |
| 42 |
} |
| 43 |
if result.ID != man.ID || result.Age != 20 { |
| 44 |
t.Fatalf("expected ID %d and Age 20, got ID %d and age", result.ID, result.Age) |
| 45 |
} |
| 46 |
} |