mirror of https://github.com/go-gorm/gorm.git
Test create polymorphic has one
This commit is contained in:
parent
fb44625c33
commit
952df527db
|
@ -73,6 +73,8 @@ func SaveAfterAssociations(db *gorm.DB) {
|
||||||
if ref.OwnPrimaryKey {
|
if ref.OwnPrimaryKey {
|
||||||
fv, _ := ref.PrimaryKey.ValueOf(db.Statement.ReflectValue)
|
fv, _ := ref.PrimaryKey.ValueOf(db.Statement.ReflectValue)
|
||||||
ref.ForeignKey.Set(f, fv)
|
ref.ForeignKey.Set(f, fv)
|
||||||
|
} else if ref.PrimaryValue != "" {
|
||||||
|
ref.ForeignKey.Set(f, ref.PrimaryValue)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
package tests
|
package tests
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/jinzhu/gorm"
|
"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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
|
@ -44,6 +44,7 @@ type Pet struct {
|
||||||
|
|
||||||
type Toy struct {
|
type Toy struct {
|
||||||
gorm.Model
|
gorm.Model
|
||||||
|
Name string
|
||||||
OwnerID string
|
OwnerID string
|
||||||
OwnerType string
|
OwnerType string
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue