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

Function TestClauseAssociationSetUpdateAndDelete

tests/association_generics_test.go:584–612  ·  view source on GitHub ↗

OpDelete/OpUpdate should work for associations

(t *testing.T)

Source from the content-addressed store, hash-verified

582
583// OpDelete/OpUpdate should work for associations
584func TestClauseAssociationSetUpdateAndDelete(t *testing.T) {
585 ctx := context.Background()
586 user := User{Name: "TestClauseAssociationSetUpdateAndDelete", Age: 25}
587 user.Pets = []*Pet{{Name: "before"}}
588 if err := DB.Create(&user).Error; err != nil {
589 t.Fatalf("create user: %v", err)
590 }
591 AssertAssociationCount(t, user, "Pets", 1, "before update/delete")
592
593 // Update pet name via OpUpdate
594 updOp := clause.Association{Association: "Pets", Type: clause.OpUpdate, Set: []clause.Assignment{{Column: clause.Column{Name: "name"}, Value: "x"}}}
595 if _, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(updOp).Update(ctx); err != nil {
596 t.Fatalf("OpUpdate failed: %v", err)
597 }
598 var got User
599 if err := DB.Preload("Pets").First(&got, user.ID).Error; err != nil {
600 t.Fatalf("load user: %v", err)
601 }
602 if len(got.Pets) != 1 || got.Pets[0].Name != "x" {
603 t.Fatalf("expected updated pet name, got %+v", got.Pets)
604 }
605
606 // Delete pets via OpDelete
607 delOp := clause.Association{Association: "Pets", Type: clause.OpDelete}
608 if _, err := gorm.G[User](DB).Where("id = ?", user.ID).Set(delOp).Update(ctx); err != nil {
609 t.Fatalf("OpDelete failed: %v", err)
610 }
611 AssertAssociationCount(t, user, "Pets", 0, "after delete")
612}
613
614// HasOne: update and delete NamedPet via OpUpdate/OpDelete
615func TestClauseAssociationSetUpdateAndDeleteHasOne(t *testing.T) {

Callers

nothing calls this directly

Calls 7

AssertAssociationCountFunction · 0.85
CreateMethod · 0.65
UpdateMethod · 0.65
SetMethod · 0.65
WhereMethod · 0.65
FirstMethod · 0.65
PreloadMethod · 0.65

Tested by

no test coverage detected