Add more tests for belongs to relations with partial customized foreign keys

This commit is contained in:
Jinzhu 2016-01-04 12:29:57 +08:00
parent 8aa7b475d4
commit 4c52351b3e
1 changed files with 47 additions and 4 deletions

View File

@ -145,6 +145,14 @@ type PromotionDiscount struct {
Name string Name string
Coupons []*PromotionCoupon `gorm:"ForeignKey:discount_id"` Coupons []*PromotionCoupon `gorm:"ForeignKey:discount_id"`
Rule *PromotionRule `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 { 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.DropTable(&PromotionDiscount{}, &PromotionRule{})
DB.AutoMigrate(&PromotionDiscount{}, &PromotionRule{}) DB.AutoMigrate(&PromotionDiscount{}, &PromotionRule{})
@ -235,3 +243,38 @@ func TestOneToOneWithPartialCustomizedColumn(t *testing.T) {
t.Errorf("should preload discount from rule") 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")
}
}