diff --git a/customize_column_test.go b/customize_column_test.go index 29400cd0..93bab2e1 100644 --- a/customize_column_test.go +++ b/customize_column_test.go @@ -142,9 +142,17 @@ func TestOneToOneWithCustomizedColumn(t *testing.T) { type PromotionDiscount struct { gorm.Model - Name string - Coupons []*PromotionCoupon `gorm:"ForeignKey:discount_id"` - Rule *PromotionRule `gorm:"ForeignKey:discount_id"` + Name string + Coupons []*PromotionCoupon `gorm:"ForeignKey:discount_id"` + Rule *PromotionRule `gorm:"ForeignKey:discount_id"` + Benefits []PromotionBenefit `gorm:"ForeignKey:promotion_id"` +} + +type PromotionBenefit struct { + gorm.Model + Name string + PromotionID uint + Discount PromotionDiscount `gorm:"ForeignKey:promotion_id"` } type PromotionCoupon struct { @@ -198,7 +206,7 @@ func TestOneToManyWithCustomizedColumn(t *testing.T) { } } -func TestOneToOneWithPartialCustomizedColumn(t *testing.T) { +func TestHasOneWithPartialCustomizedColumn(t *testing.T) { DB.DropTable(&PromotionDiscount{}, &PromotionRule{}) DB.AutoMigrate(&PromotionDiscount{}, &PromotionRule{}) @@ -235,3 +243,38 @@ func TestOneToOneWithPartialCustomizedColumn(t *testing.T) { t.Errorf("should preload discount from rule") } } + +func TestBelongsToWithPartialCustomizedColumn(t *testing.T) { + DB.DropTable(&PromotionDiscount{}, &PromotionBenefit{}) + DB.AutoMigrate(&PromotionDiscount{}, &PromotionBenefit{}) + + discount := PromotionDiscount{ + Name: "Happy New Year 3", + Benefits: []PromotionBenefit{ + {Name: "free cod"}, + {Name: "free shipping"}, + }, + } + + if err := DB.Create(&discount).Error; err != nil { + t.Errorf("no error should happen but got %v", err) + } + + var discount1 PromotionDiscount + if err := DB.Preload("Benefits").First(&discount1, "id = ?", discount.ID).Error; err != nil { + t.Errorf("no error should happen but got %v", err) + } + + if len(discount.Benefits) != 2 { + t.Errorf("should find two benefits") + } + + var benefit PromotionBenefit + if err := DB.Preload("Discount").First(&benefit, "name = ?", "free cod").Error; err != nil { + t.Errorf("no error should happen but got %v", err) + } + + if benefit.Discount.Name != "Happy New Year 3" { + t.Errorf("should preload discount from coupon") + } +}