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

Function TestGenericsNestedJoins

tests/generics_test.go:461–535  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

459}
460
461func TestGenericsNestedJoins(t *testing.T) {
462 users := []User{
463 {
464 Name: "generics-nested-joins-1",
465 Manager: &User{
466 Name: "generics-nested-joins-manager-1",
467 Company: Company{
468 Name: "generics-nested-joins-manager-company-1",
469 },
470 NamedPet: &Pet{
471 Name: "generics-nested-joins-manager-namepet-1",
472 Toy: Toy{
473 Name: "generics-nested-joins-manager-namepet-toy-1",
474 },
475 },
476 },
477 NamedPet: &Pet{Name: "generics-nested-joins-namepet-1", Toy: Toy{Name: "generics-nested-joins-namepet-toy-1"}},
478 },
479 {
480 Name: "generics-nested-joins-2",
481 Manager: GetUser("generics-nested-joins-manager-2", Config{Company: true, NamedPet: true}),
482 NamedPet: &Pet{Name: "generics-nested-joins-namepet-2", Toy: Toy{Name: "generics-nested-joins-namepet-toy-2"}},
483 },
484 }
485
486 ctx := context.Background()
487 db := gorm.G[User](DB)
488 db.CreateInBatches(ctx, &users, 100)
489
490 var userIDs []uint
491 for _, user := range users {
492 userIDs = append(userIDs, user.ID)
493 }
494
495 users2, err := db.Joins(clause.LeftJoin.Association("Manager"), nil).
496 Joins(clause.LeftJoin.Association("Manager.Company"), nil).
497 Joins(clause.LeftJoin.Association("Manager.NamedPet.Toy"), nil).
498 Joins(clause.LeftJoin.Association("NamedPet.Toy"), nil).
499 Joins(clause.LeftJoin.Association("NamedPet").As("t"), nil).
500 Where(map[string]any{"id": userIDs}).Find(ctx)
501
502 if err != nil {
503 t.Fatalf("Failed to load with joins, got error: %v", err)
504 } else if len(users2) != len(users) {
505 t.Fatalf("Failed to load join users, got: %v, expect: %v", len(users2), len(users))
506 }
507
508 sort.Slice(users2, func(i, j int) bool {
509 return users2[i].ID > users2[j].ID
510 })
511
512 sort.Slice(users, func(i, j int) bool {
513 return users[i].ID > users[j].ID
514 })
515
516 for idx, user := range users {
517 // user
518 CheckUser(t, user, users2[idx])

Callers

nothing calls this directly

Calls 9

GetUserFunction · 0.85
CheckUserFunction · 0.85
CheckPetFunction · 0.85
AsMethod · 0.80
CreateInBatchesMethod · 0.65
FindMethod · 0.65
WhereMethod · 0.65
JoinsMethod · 0.65
AssociationMethod · 0.45

Tested by

no test coverage detected