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

Function TestHasManyAssociation

tests/associations_has_many_test.go:10–120  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

8)
9
10func TestHasManyAssociation(t *testing.T) {
11 user := *GetUser("hasmany", Config{Pets: 2})
12
13 if err := DB.Create(&user).Error; err != nil {
14 t.Fatalf("errors happened when create: %v", err)
15 }
16
17 CheckUser(t, user, user)
18
19 // Find
20 var user2 User
21 DB.Find(&user2, "id = ?", user.ID)
22 DB.Model(&user2).Association("Pets").Find(&user2.Pets)
23 CheckUser(t, user2, user)
24
25 var pets []Pet
26 DB.Model(&user).Where("name = ?", user.Pets[0].Name).Association("Pets").Find(&pets)
27
28 if len(pets) != 1 {
29 t.Fatalf("should only find one pets, but got %v", len(pets))
30 }
31
32 CheckPet(t, pets[0], *user.Pets[0])
33
34 if count := DB.Model(&user).Where("name = ?", user.Pets[1].Name).Association("Pets").Count(); count != 1 {
35 t.Fatalf("should only find one pets, but got %v", count)
36 }
37
38 if count := DB.Model(&user).Where("name = ?", "not found").Association("Pets").Count(); count != 0 {
39 t.Fatalf("should only find no pet with invalid conditions, but got %v", count)
40 }
41
42 // Count
43 AssertAssociationCount(t, user, "Pets", 2, "")
44
45 // Append
46 pet := Pet{Name: "pet-has-many-append"}
47
48 if err := DB.Model(&user2).Association("Pets").Append(&pet); err != nil {
49 t.Fatalf("Error happened when append account, got %v", err)
50 }
51
52 if pet.ID == 0 {
53 t.Fatalf("Pet's ID should be created")
54 }
55
56 user.Pets = append(user.Pets, &pet)
57 CheckUser(t, user2, user)
58
59 AssertAssociationCount(t, user, "Pets", 3, "AfterAppend")
60
61 pets2 := []Pet{{Name: "pet-has-many-append-1-1"}, {Name: "pet-has-many-append-1-1"}}
62
63 if err := DB.Model(&user2).Association("Pets").Append(&pets2); err != nil {
64 t.Fatalf("Error happened when append pet, got %v", err)
65 }
66
67 for _, pet := range pets2 {

Callers

nothing calls this directly

Calls 14

GetUserFunction · 0.85
CheckUserFunction · 0.85
CheckPetFunction · 0.85
AssertAssociationCountFunction · 0.85
ModelMethod · 0.80
AppendMethod · 0.80
ClearMethod · 0.80
CreateMethod · 0.65
FindMethod · 0.65
WhereMethod · 0.65
CountMethod · 0.65
ReplaceMethod · 0.65

Tested by

no test coverage detected