forked from mirror/gorm
Add more tests for belongs to relations with partial customized foreign keys
This commit is contained in:
parent
8aa7b475d4
commit
4c52351b3e
|
@ -145,6 +145,14 @@ type PromotionDiscount struct {
|
|||
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")
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue