diff --git a/model_struct.go b/model_struct.go index aa124625..50437778 100644 --- a/model_struct.go +++ b/model_struct.go @@ -326,10 +326,10 @@ func (scope *Scope) GetModelStruct() *ModelStruct { field.Relationship = relationship } else { if len(foreignKeys) == 0 { - for _, field := range toScope.PrimaryFields() { - if foreignField := getForeignField(modelStruct.ModelType.Name()+field.Name, toScope.GetStructFields()); foreignField != nil { - relationship.AssociationForeignFieldNames = append(relationship.AssociationForeignFieldNames, field.Name) - relationship.AssociationForeignDBNames = append(relationship.AssociationForeignDBNames, field.DBName) + for _, f := range scope.PrimaryFields() { + if foreignField := getForeignField(modelStruct.ModelType.Name()+f.Name, toScope.GetStructFields()); foreignField != nil { + relationship.AssociationForeignFieldNames = append(relationship.AssociationForeignFieldNames, f.Name) + relationship.AssociationForeignDBNames = append(relationship.AssociationForeignDBNames, f.DBName) relationship.ForeignFieldNames = append(relationship.ForeignFieldNames, foreignField.Name) relationship.ForeignDBNames = append(relationship.ForeignDBNames, foreignField.DBName) foreignField.IsForeignKey = true diff --git a/preload.go b/preload.go index 0a302ab2..0db6fbde 100644 --- a/preload.go +++ b/preload.go @@ -101,6 +101,7 @@ func makeSlice(typ reflect.Type) interface{} { func (scope *Scope) handleHasOnePreload(field *Field, conditions []interface{}) { relation := field.Relationship + primaryKeys := scope.getColumnAsArray(relation.AssociationForeignFieldNames) if len(primaryKeys) == 0 { return @@ -168,7 +169,7 @@ func (scope *Scope) handleBelongsToPreload(field *Field, conditions []interface{ } results := makeSlice(field.Struct.Type) - scope.Err(scope.NewDB().Where(fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relation.ForeignDBNames), toQueryMarks(primaryKeys)), toQueryValues(primaryKeys)...).Find(results, conditions...).Error) + scope.Err(scope.NewDB().Where(fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relation.AssociationForeignDBNames), toQueryMarks(primaryKeys)), toQueryValues(primaryKeys)...).Find(results, conditions...).Error) resultValues := reflect.Indirect(reflect.ValueOf(results)) for i := 0; i < resultValues.Len(); i++ {