forked from mirror/gorm
Support include struct type in the foreign key to avoid ambiguous
This commit is contained in:
parent
1ad419004f
commit
0f3a9a8d02
|
@ -419,8 +419,17 @@ func (scope *Scope) typeName() string {
|
||||||
|
|
||||||
func (scope *Scope) related(value interface{}, foreignKeys ...string) *Scope {
|
func (scope *Scope) related(value interface{}, foreignKeys ...string) *Scope {
|
||||||
toScope := scope.db.NewScope(value)
|
toScope := scope.db.NewScope(value)
|
||||||
|
fromScopeType := scope.typeName()
|
||||||
|
toScopeType := toScope.typeName()
|
||||||
|
scopeType := ""
|
||||||
|
|
||||||
for _, foreignKey := range append(foreignKeys, toScope.typeName()+"Id", scope.typeName()+"Id") {
|
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 {
|
if field, ok := scope.FieldByName(foreignKey); ok {
|
||||||
relationship := field.Relationship
|
relationship := field.Relationship
|
||||||
if relationship != nil && relationship.ForeignKey != "" {
|
if relationship != nil && relationship.ForeignKey != "" {
|
||||||
|
@ -446,13 +455,16 @@ func (scope *Scope) related(value interface{}, foreignKeys ...string) *Scope {
|
||||||
return scope
|
return scope
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if scopeType == "" || scopeType == toScopeType {
|
||||||
// has many
|
// has many
|
||||||
if toScope.HasColumn(foreignKey) {
|
if toScope.HasColumn(foreignKey) {
|
||||||
sql := fmt.Sprintf("%v = ?", scope.Quote(ToSnake(foreignKey)))
|
sql := fmt.Sprintf("%v = ?", scope.Quote(ToSnake(foreignKey)))
|
||||||
return toScope.inlineCondition(sql, scope.PrimaryKeyValue()).callCallbacks(scope.db.parent.callback.queries)
|
return toScope.inlineCondition(sql, scope.PrimaryKeyValue()).callCallbacks(scope.db.parent.callback.queries)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
scope.Err(fmt.Errorf("invalid association %v", foreignKeys))
|
scope.Err(fmt.Errorf("invalid association %v", foreignKeys))
|
||||||
return scope
|
return scope
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue