Should ignore association conditions when querying with struct

This commit is contained in:
Jinzhu 2020-08-13 18:09:04 +08:00
parent dea93edb6a
commit 2c4e857125
2 changed files with 22 additions and 6 deletions

View File

@ -309,10 +309,10 @@ func (stmt *Statement) BuildCondition(query interface{}, args ...interface{}) (c
for _, field := range s.Fields {
if field.Readable {
if v, isZero := field.ValueOf(reflectValue); !isZero {
if field.DBName == "" {
conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.Name}, Value: v})
} else {
if field.DBName != "" {
conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.DBName}, Value: v})
} else if field.DataType != "" {
conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.Name}, Value: v})
}
}
}
@ -322,10 +322,10 @@ func (stmt *Statement) BuildCondition(query interface{}, args ...interface{}) (c
for _, field := range s.Fields {
if field.Readable {
if v, isZero := field.ValueOf(reflectValue.Index(i)); !isZero {
if field.DBName == "" {
conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.Name}, Value: v})
} else {
if field.DBName != "" {
conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.DBName}, Value: v})
} else if field.DataType != "" {
conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.Name}, Value: v})
}
}
}

View File

@ -103,6 +103,22 @@ func TestFind(t *testing.T) {
})
}
func TestQueryWithAssociation(t *testing.T) {
user := *GetUser("query_with_association", Config{Account: true, Pets: 2, Toys: 1, Company: true, Manager: true, Team: 2, Languages: 1, Friends: 3})
if err := DB.Create(&user).Error; err != nil {
t.Fatalf("errors happened when create user: %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)
}
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 TestFindInBatches(t *testing.T) {
var users = []User{
*GetUser("find_in_batches", Config{}),