MCPcopy
hub / github.com/go-gorm/gorm / TestBelongsToAssociationUnscoped

Function TestBelongsToAssociationUnscoped

tests/associations_belongs_to_test.go:255–306  ·  tests/associations_belongs_to_test.go::TestBelongsToAssociationUnscoped
(t *testing.T)

Source from the content-addressed store, hash-verified

253}
254
255func TestBelongsToAssociationUnscoped(t *testing.T) {
256 type ItemParent struct {
257 gorm.Model
258 Logo string `gorm:"not null;type:varchar(50)"`
259 }
260 type ItemChild struct {
261 gorm.Model
262 Name string `gorm:"type:varchar(50)"`
263 ItemParentID uint
264 ItemParent ItemParent
265 }
266
267 tx := DB.Session(&gorm.Session{})
268 tx.Migrator().DropTable(&ItemParent{}, &ItemChild{})
269 tx.AutoMigrate(&ItemParent{}, &ItemChild{})
270
271 item := ItemChild{
272 Name: "name",
273 ItemParent: ItemParent{
274 Logo: "logo",
275 },
276 }
277 if err := tx.Create(&item).Error; err != nil {
278 t.Fatalf("failed to create items, got error: %v", err)
279 }
280
281 // test replace
282 if err := tx.Model(&item).Association("ItemParent").Unscoped().Replace(&ItemParent{
283 Logo: "updated logo",
284 }); err != nil {
285 t.Errorf("failed to replace item parent, got error: %v", err)
286 }
287
288 var parents []ItemParent
289 if err := tx.Find(&parents).Error; err != nil {
290 t.Errorf("failed to find item parent, got error: %v", err)
291 }
292 if len(parents) != 1 {
293 t.Errorf("expected %d parents, got %d", 1, len(parents))
294 }
295
296 // test delete
297 if err := tx.Model(&item).Association("ItemParent").Unscoped().Delete(&parents); err != nil {
298 t.Errorf("failed to delete item parent, got error: %v", err)
299 }
300 if err := tx.Find(&parents).Error; err != nil {
301 t.Errorf("failed to find item parent, got error: %v", err)
302 }
303 if len(parents) != 0 {
304 t.Errorf("expected %d parents, got %d", 0, len(parents))
305 }
306}

Callers

nothing calls this directly

Calls 11

SessionMethod · 0.80
ModelMethod · 0.80
DropTableMethod · 0.65
MigratorMethod · 0.65
AutoMigrateMethod · 0.65
CreateMethod · 0.65
ReplaceMethod · 0.65
FindMethod · 0.65
DeleteMethod · 0.65
UnscopedMethod · 0.45
AssociationMethod · 0.45

Tested by

no test coverage detected