From 660ee1ed733f3e2fdd7f63d03a0a745ad6d6c1de Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sat, 23 Nov 2013 21:38:31 +0800 Subject: [PATCH] Add Method NewRecord --- README.md | 12 ++++++++++++ gorm_test.go | 9 +++++++++ main.go | 4 ++++ 3 files changed, 25 insertions(+) diff --git a/README.md b/README.md index 28ac7592..43ba6e27 100644 --- a/README.md +++ b/README.md @@ -137,6 +137,18 @@ user := User{Name: "jinzhu", Age: 18, Birthday: time.Now()} db.Save(&user) ``` +### NewRecord + +Returns true if object hasn’t been saved yet (`Id` is blank) + +```go +user := User{Name: "jinzhu", Age: 18, Birthday: time.Now()} +db.NewRecord(user) // => true + +db.Save(&user) +db.NewRecord(user) // => false +``` + ### Create With SubStruct Refer [Query With Related](#query-with-related) for how to find associations diff --git a/gorm_test.go b/gorm_test.go index 37571f5a..472df1f2 100644 --- a/gorm_test.go +++ b/gorm_test.go @@ -161,11 +161,20 @@ func TestFirstAndLast(t *testing.T) { func TestCreateAndUpdate(t *testing.T) { name, name2, new_name := "update", "update2", "new_update" user := User{Name: name, Age: 1, PasswordHash: []byte{'f', 'a', 'k', '4'}} + + if !db.NewRecord(user) { + t.Error("User should be new record") + } + db.Save(&user) if user.Id == 0 { t.Errorf("Should have ID after create") } + if db.NewRecord(user) { + t.Error("User should not new record after save") + } + var u User db.First(&u, user.Id) if !reflect.DeepEqual(u.PasswordHash, []byte{'f', 'a', 'k', '4'}) { diff --git a/main.go b/main.go index be8b8981..b966e923 100644 --- a/main.go +++ b/main.go @@ -238,6 +238,10 @@ func (s *DB) Rollback() *DB { return s } +func (s *DB) NewRecord(value interface{}) bool { + return s.clone().do(value).model.primaryKeyZero() +} + // Migrations func (s *DB) CreateTable(value interface{}) *DB { return s.clone().do(value).createTable().db