Support include struct type in the foreign key to avoid ambiguous

This commit is contained in:
Jinzhu 2014-09-08 11:19:05 +08:00
parent 1ad419004f
commit 0f3a9a8d02
1 changed files with 36 additions and 24 deletions

View File

@ -419,8 +419,17 @@ func (scope *Scope) typeName() string {
func (scope *Scope) related(value interface{}, foreignKeys ...string) *Scope {
toScope := scope.db.NewScope(value)
fromScopeType := scope.typeName()
toScopeType := toScope.typeName()
scopeType := ""
for _, foreignKey := range append(foreignKeys, toScope.typeName()+"Id", scope.typeName()+"Id") {
if keys := strings.Split(foreignKey, "."); len(keys) > 1 {
scopeType = keys[0]
foreignKey = keys[1]
}
if scopeType == "" || scopeType == fromScopeType {
if field, ok := scope.FieldByName(foreignKey); ok {
relationship := field.Relationship
if relationship != nil && relationship.ForeignKey != "" {
@ -446,13 +455,16 @@ func (scope *Scope) related(value interface{}, foreignKeys ...string) *Scope {
return scope
}
}
}
if scopeType == "" || scopeType == toScopeType {
// has many
if toScope.HasColumn(foreignKey) {
sql := fmt.Sprintf("%v = ?", scope.Quote(ToSnake(foreignKey)))
return toScope.inlineCondition(sql, scope.PrimaryKeyValue()).callCallbacks(scope.db.parent.callback.queries)
}
}
}
scope.Err(fmt.Errorf("invalid association %v", foreignKeys))
return scope
}