Add tests for override belogns to foreign keys with tag

This commit is contained in:
Jinzhu 2016-03-07 23:35:31 +08:00
parent 946909f1e8
commit 2c089573cd
2 changed files with 49 additions and 1 deletions

View File

@ -5,6 +5,8 @@ import (
"reflect"
"sort"
"testing"
"github.com/jinzhu/gorm"
)
func TestBelongsTo(t *testing.T) {
@ -177,6 +179,49 @@ func TestBelongsTo(t *testing.T) {
}
}
func TestBelongsToOverrideForeignKey1(t *testing.T) {
type Profile struct {
gorm.Model
Name string
}
type User struct {
gorm.Model
Profile Profile `gorm:"ForeignKey:ProfileRefer"`
ProfileRefer int
}
DB.AutoMigrate(&User{})
DB.AutoMigrate(&Profile{})
var user = User{Model: gorm.Model{ID: 1}, ProfileRefer: 10}
if err := DB.Model(&user).Association("Profile").Find(&[]Profile{}).Error; err != nil {
t.Errorf("Override belongs to foreign key with tag")
}
}
func TestBelongsToOverrideForeignKey2(t *testing.T) {
type Profile struct {
gorm.Model
Refer string
Name string
}
type User struct {
gorm.Model
Profile Profile `gorm:"ForeignKey:ProfileID;AssociationForeignKey:Refer"`
ProfileID int
}
DB.AutoMigrate(&User{})
DB.AutoMigrate(&Profile{})
var user = User{Model: gorm.Model{ID: 1}, ProfileID: 10}
if err := DB.Model(&user).Association("Profile").Find(&[]Profile{}).Error; err != nil {
t.Errorf("Override belongs to foreign key with tag")
}
}
func TestHasOne(t *testing.T) {
user := User{
Name: "has one",

View File

@ -447,7 +447,10 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
if len(associationForeignKeys) == 0 {
for _, foreignKey := range foreignKeys {
if strings.HasPrefix(foreignKey, field.Name) {
associationForeignKeys = append(associationForeignKeys, strings.TrimPrefix(foreignKey, field.Name))
associationForeignKey := strings.TrimPrefix(foreignKey, field.Name)
if foreignField := getForeignField(associationForeignKey, toFields); foreignField != nil {
associationForeignKeys = append(associationForeignKeys, associationForeignKey)
}
}
}
if len(associationForeignKeys) == 0 && len(foreignKeys) == 1 {