| 1476 | } |
| 1477 | |
| 1478 | func TestPreloadManyToManyCallbacks(t *testing.T) { |
| 1479 | type ( |
| 1480 | Level2 struct { |
| 1481 | ID uint |
| 1482 | Name string |
| 1483 | } |
| 1484 | Level1 struct { |
| 1485 | ID uint |
| 1486 | Name string |
| 1487 | Level2s []Level2 `gorm:"many2many:level1_level2s"` |
| 1488 | } |
| 1489 | ) |
| 1490 | |
| 1491 | DB.Migrator().DropTable("level1_level2s", &Level2{}, &Level1{}) |
| 1492 | |
| 1493 | if err := DB.AutoMigrate(new(Level1), new(Level2)); err != nil { |
| 1494 | t.Error(err) |
| 1495 | } |
| 1496 | |
| 1497 | lvl := Level1{ |
| 1498 | Name: "l1", |
| 1499 | Level2s: []Level2{ |
| 1500 | {Name: "l2-1"}, {Name: "l2-2"}, |
| 1501 | }, |
| 1502 | } |
| 1503 | DB.Save(&lvl) |
| 1504 | |
| 1505 | var called int64 |
| 1506 | DB.Callback().Query().After("gorm:query").Register("TestPreloadManyToManyCallbacks", func(_ *gorm.DB) { |
| 1507 | atomic.AddInt64(&called, 1) |
| 1508 | }) |
| 1509 | |
| 1510 | DB.Preload("Level2s").First(&Level1{}, "id = ?", lvl.ID) |
| 1511 | |
| 1512 | if called != 3 { |
| 1513 | t.Errorf("Wanted callback to be called 3 times but got %d", called) |
| 1514 | } |
| 1515 | } |