Test create polymorphic has one

This commit is contained in:
Jinzhu 2020-04-17 08:40:07 +08:00
parent fb44625c33
commit 952df527db
3 changed files with 25 additions and 0 deletions

View File

@ -73,6 +73,8 @@ func SaveAfterAssociations(db *gorm.DB) {
if ref.OwnPrimaryKey {
fv, _ := ref.PrimaryKey.ValueOf(db.Statement.ReflectValue)
ref.ForeignKey.Set(f, fv)
} else if ref.PrimaryValue != "" {
ref.ForeignKey.Set(f, ref.PrimaryValue)
}
}
}

View File

@ -1,6 +1,7 @@
package tests
import (
"fmt"
"testing"
"github.com/jinzhu/gorm"
@ -106,4 +107,25 @@ func TestCreateAssociations(t *testing.T, db *gorm.DB) {
}
}
})
t.Run("Create-HasOneAssociation-Polymorphic", func(t *testing.T) {
var pet = Pet{
Name: "create",
Toy: Toy{Name: "Create-HasOneAssociation-Polymorphic"},
}
if err := db.Create(&pet).Error; err != nil {
t.Fatalf("errors happened when create: %v", err)
}
if pet.Toy.OwnerID != fmt.Sprint(pet.ID) || pet.Toy.OwnerType != "pets" {
t.Errorf("Failed to create polymorphic has one association - toy owner id %v, owner type %v", pet.Toy.OwnerID, pet.Toy.OwnerType)
} else {
var toy Toy
db.First(&toy, "owner_id = ? and owner_type = ?", pet.Toy.OwnerID, pet.Toy.OwnerType)
if toy.Name != "Create-HasOneAssociation-Polymorphic" {
t.Errorf("Failed to query saved polymorphic has one association")
}
}
})
}

View File

@ -44,6 +44,7 @@ type Pet struct {
type Toy struct {
gorm.Model
Name string
OwnerID string
OwnerType string
}