Add inline condition support for Preload

This commit is contained in:
Jinzhu 2015-02-11 19:08:42 +08:00
parent 87b23edd3b
commit 24e0de116a
2 changed files with 17 additions and 4 deletions

View File

@ -36,7 +36,7 @@ func Preload(scope *Scope) {
}
if scope.Search.Preload != nil {
for key := range scope.Search.Preload {
for key, conditions := range scope.Search.Preload {
for _, field := range fields {
if field.Name == key && field.Relationship != nil {
results := makeSlice(field.Field)
@ -47,7 +47,7 @@ func Preload(scope *Scope) {
switch relation.Kind {
case "has_one":
condition := fmt.Sprintf("%v IN (?)", scope.Quote(relation.ForeignDBName()))
scope.NewDB().Find(results, condition, scope.getColumnAsArray(primaryName))
scope.NewDB().Where(condition, scope.getColumnAsArray(primaryName)).Find(results, conditions...)
resultValues := reflect.Indirect(reflect.ValueOf(results))
for i := 0; i < resultValues.Len(); i++ {
@ -67,7 +67,7 @@ func Preload(scope *Scope) {
}
case "has_many":
condition := fmt.Sprintf("%v IN (?)", scope.Quote(relation.ForeignDBName()))
scope.NewDB().Find(results, condition, scope.getColumnAsArray(primaryName))
scope.NewDB().Where(condition, scope.getColumnAsArray(primaryName)).Find(results, conditions...)
resultValues := reflect.Indirect(reflect.ValueOf(results))
if isSlice {
for i := 0; i < resultValues.Len(); i++ {
@ -87,7 +87,7 @@ func Preload(scope *Scope) {
scope.SetColumn(field, resultValues)
}
case "belongs_to":
scope.NewDB().Find(results, scope.getColumnAsArray(relation.ForeignKey))
scope.NewDB().Where(scope.getColumnAsArray(relation.ForeignKey)).Find(results, conditions...)
resultValues := reflect.Indirect(reflect.ValueOf(results))
for i := 0; i < resultValues.Len(); i++ {
result := resultValues.Index(i)

View File

@ -84,4 +84,17 @@ func TestPreload(t *testing.T) {
for _, user := range users2 {
checkUserHasPreloadData(*user, t)
}
var users3 []*User
DB.Where("role = ?", "Preload").Preload("Emails", "email = ?", user3.Emails[0].Email).Find(&users3)
for _, user := range users3 {
if user.Name == user3.Name {
if len(user.Emails) != 1 {
t.Errorf("should only preload one emails for user3 when with condition")
}
} else if len(user.Emails) != 0 {
t.Errorf("should not preload any emails for other users when with condition")
}
}
}