GORM Playground Link
https://github.com/go-gorm/playground/pull/412
Description
If you soft-delete a Has-One relationship, the deleted association won't be loaded if you use Preload(). If you use Joins(), though, it won't respect the soft deletion.
var account Account{Number:"77"}
DB.Create(&account)
user := User{ Name: "jinzhu", Account: account}
DB.Create(&user)
DB.Delete(&account)
// Works, no account in User
DB.Preload("Account").First(&result, user.ID)
// Doesn't work, account is hydrated even though it's been soft-deleted
DB.Joins("Account").First(&result, user.ID)
Comment From: jinzhu
seems correct, there is a typo in your demo.
Comment From: awmcclain
seems correct, there is a typo in your demo.
That code you pasted isn't in my playground or in any of the code I submitted.
func TestGORM(t *testing.T) {
account := Account{Number: "77"}
DB.Create(&account)
user := User{Name: "jinzhu", Account: account}
DB.Create(&user)
var result, result2, result3, result4 User
if err := DB.Preload("Account").First(&result, user.ID).Error; err != nil {
t.Errorf("Failed, got error: %v", err)
}
if result.Account.ID != account.ID {
t.Fatalf("Failed using preload, Account should be valid")
}
if err := DB.Joins("Account").First(&result2, user.ID).Error; err != nil {
t.Fatalf("Failed, got error: %v", err)
}
if result2.Account.ID != account.ID {
t.Fatalf("Failed using joins, account should be valid")
}
// Delete the account
DB.Delete(&account)
if err := DB.Preload("Account").First(&result3, user.ID).Error; err != nil {
t.Fatalf("Failed, got error: %v", err)
}
if result3.Account.ID != 0 {
t.Errorf("Failed using preload, Account should be 0 got: %v", result3)
}
if err := DB.Joins("Account").First(&result4, user.ID).Error; err != nil {
t.Fatalf("Failed, got error: %v", err)
}
if result4.Account.ID != 0 {
t.Errorf("Failed using joins, account should be 0, got: %v", result4)
}
}
Comment From: jinzhu
Sorry, seems I replied on a wrong thread...
Comment From: awmcclain
Ah yes, sorry, I submitted two issues right next to each other!
Comment From: jinzhu
Fixed in latest master, thank you for your report.