Add Method NewRecord

This commit is contained in:
Jinzhu 2013-11-23 21:38:31 +08:00
parent 66ac04ba05
commit 660ee1ed73
3 changed files with 25 additions and 0 deletions

View File

@ -137,6 +137,18 @@ user := User{Name: "jinzhu", Age: 18, Birthday: time.Now()}
db.Save(&user)
```
### NewRecord
Returns true if object hasnt 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

View File

@ -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'}) {

View File

@ -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