Skip to content

Commit

Permalink
Should ignore association conditions when querying with struct
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Aug 13, 2020
1 parent bf55f35 commit 6f4358e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
18 changes: 18 additions & 0 deletions query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,24 @@ func TestFirstAndLast(t *testing.T) {
}
}

func TestQueryWithAssociation(t *testing.T) {
user := &User{Name: "user1", Emails: []Email{{Email: "user1@example.com"}}, Company: Company{Name: "company"}}

if err := DB.Create(&user).Error; err != nil {
t.Fatalf("errors happened when create user: %v", err)
}

user.CreatedAt = time.Time{}
user.UpdatedAt = time.Time{}
if err := DB.Where(&user).First(&User{}).Error; err != nil {
t.Errorf("search with struct with association should returns no error, but got %v", err)
}

if err := DB.Where(user).First(&User{}).Error; err != nil {
t.Errorf("search with struct with association should returns no error, but got %v", err)
}
}

func TestFirstAndLastWithNoStdPrimaryKey(t *testing.T) {
DB.Save(&Animal{Name: "animal1"})
DB.Save(&Animal{Name: "animal2"})
Expand Down
2 changes: 1 addition & 1 deletion scope.go
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,7 @@ func (scope *Scope) buildCondition(clause map[string]interface{}, include bool)
}
scopeQuotedTableName := newScope.QuotedTableName()
for _, field := range newScope.Fields() {
if !field.IsIgnored && !field.IsBlank {
if !field.IsIgnored && !field.IsBlank && field.Relationship == nil {
sqls = append(sqls, fmt.Sprintf("(%v.%v %s %v)", scopeQuotedTableName, scope.Quote(field.DBName), equalSQL, scope.AddToVars(field.Field.Interface())))
}
}
Expand Down

0 comments on commit 6f4358e

Please sign in to comment.