fixed belongs_to & has_one reversed if field same
This commit is contained in:
		
							parent
							
								
									70e93e73d8
								
							
						
					
					
						commit
						a222c758bb
					
				@ -7,6 +7,7 @@ import (
 | 
			
		||||
 | 
			
		||||
	"github.com/jinzhu/inflection"
 | 
			
		||||
	"gorm.io/gorm/clause"
 | 
			
		||||
	"gorm.io/gorm/utils"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
// RelationshipType relationship type
 | 
			
		||||
@ -404,11 +405,14 @@ func (schema *Schema) guessRelation(relation *Relationship, field *Field, cgl gu
 | 
			
		||||
 | 
			
		||||
	if len(relation.foreignKeys) > 0 {
 | 
			
		||||
		for _, foreignKey := range relation.foreignKeys {
 | 
			
		||||
			if f := foreignSchema.LookUpField(foreignKey); f != nil {
 | 
			
		||||
				foreignFields = append(foreignFields, f)
 | 
			
		||||
			} else {
 | 
			
		||||
			ff := foreignSchema.LookUpField(foreignKey)
 | 
			
		||||
			pf := primarySchema.LookUpField(foreignKey)
 | 
			
		||||
			isKeySame := utils.ExistsIn(foreignKey, &relation.primaryKeys)
 | 
			
		||||
			if ff == nil || (pf != nil && ff != nil && schema == primarySchema && primarySchema != foreignSchema && !isKeySame) {
 | 
			
		||||
				reguessOrErr()
 | 
			
		||||
				return
 | 
			
		||||
			} else {
 | 
			
		||||
				foreignFields = append(foreignFields, ff)
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
	} else {
 | 
			
		||||
 | 
			
		||||
@ -482,3 +482,22 @@ func TestSameForeignKey(t *testing.T) {
 | 
			
		||||
		},
 | 
			
		||||
	)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func TestBelongsToWithSameForeignKey(t *testing.T) {
 | 
			
		||||
	type Profile struct {
 | 
			
		||||
		gorm.Model
 | 
			
		||||
		Name         string
 | 
			
		||||
		ProfileRefer int
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	type User struct {
 | 
			
		||||
		gorm.Model
 | 
			
		||||
		Profile      Profile `gorm:"ForeignKey:ProfileRefer"`
 | 
			
		||||
		ProfileRefer int
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	checkStructRelation(t, &User{}, Relation{
 | 
			
		||||
		Name: "Profile", Type: schema.BelongsTo, Schema: "User", FieldSchema: "Profile",
 | 
			
		||||
		References: []Reference{{"ID", "Profile", "ProfileRefer", "User", "", false}},
 | 
			
		||||
	})
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -111,3 +111,15 @@ func ToString(value interface{}) string {
 | 
			
		||||
	}
 | 
			
		||||
	return ""
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func ExistsIn(a string, list *[]string) bool {
 | 
			
		||||
	if list == nil {
 | 
			
		||||
		return false
 | 
			
		||||
	}
 | 
			
		||||
	for _, b := range *list {
 | 
			
		||||
		if b == a {
 | 
			
		||||
			return true
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
	return false
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user