From c387c7d9ba8d991bdcda09d711c577f1a881f87d Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 31 Oct 2013 22:49:48 +0800 Subject: [PATCH] Polish The Not Method --- README.md | 4 ++++ do.go | 3 +++ gorm_test.go | 12 ++++++++++++ 3 files changed, 19 insertions(+) diff --git a/README.md b/README.md index b0adb8a4..4251da6c 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,10 @@ db.Not([]int64{}).First(&user) //// user -> select * from users; db.Not("name", "jinzhu").First(&user) //// user -> select * from users where name <> "jinzhu" +db.Not("name = ?", "jinzhu").First(&user) +//// user -> select * from users where NOT(name = "jinzhu") +db.Not("name <> ?", "jinzhu").First(&user) +//// user -> select * from users where NOT(name <> "jinzhu") db.Not("name", []string{"jinzhu", "jinzhu 2"}).First(&user) //// user -> select * from users where name NOT IN ("jinzhu", "jinzhu 2") db.Not(User{Name: "jinzhu"}).First(&user) diff --git a/do.go b/do.go index 1850d7f3..fb3969c6 100644 --- a/do.go +++ b/do.go @@ -434,6 +434,9 @@ func (s *Do) buildNotCondition(clause map[string]interface{}) (str string) { if regexp.MustCompile("^\\s*\\d+\\s*$").MatchString(value) { id, _ := strconv.Atoi(value) return fmt.Sprintf("(%v <> %v)", s.model.primaryKeyDb(), id) + } else if regexp.MustCompile("(?i) (=|<>|>|<|LIKE|IS) ").MatchString(value) { + str = fmt.Sprintf(" NOT (%v) ", value) + not_equal_sql = fmt.Sprintf(" NOT (%v) ", value) } else { str = fmt.Sprintf(" (%v NOT IN (?)) ", value) not_equal_sql = fmt.Sprintf(" (%v <> ?) ", value) diff --git a/gorm_test.go b/gorm_test.go index a5cc30d7..4fa3bcaf 100644 --- a/gorm_test.go +++ b/gorm_test.go @@ -958,6 +958,18 @@ func TestNot(t *testing.T) { t.Errorf("Should find all users's name not equal 3") } + users4 = []User{} + db.Not("name = ?", "3").Find(&users4) + if len(users1)-len(users4) != int(name_3_count) { + t.Errorf("Should find all users's name not equal 3") + } + + users4 = []User{} + db.Not("name <> ?", "3").Find(&users4) + if len(users4) != int(name_3_count) { + t.Errorf("Should find all users's name not equal 3") + } + db.Not(User{Name: "3"}).Find(&users5) if len(users1)-len(users5) != int(name_3_count) { t.Errorf("Should find all users's name not equal 3")