mirror of https://github.com/go-gorm/gorm.git
Add Method NewRecord
This commit is contained in:
parent
66ac04ba05
commit
660ee1ed73
12
README.md
12
README.md
|
@ -137,6 +137,18 @@ user := User{Name: "jinzhu", Age: 18, Birthday: time.Now()}
|
||||||
db.Save(&user)
|
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
|
### Create With SubStruct
|
||||||
|
|
||||||
Refer [Query With Related](#query-with-related) for how to find associations
|
Refer [Query With Related](#query-with-related) for how to find associations
|
||||||
|
|
|
@ -161,11 +161,20 @@ func TestFirstAndLast(t *testing.T) {
|
||||||
func TestCreateAndUpdate(t *testing.T) {
|
func TestCreateAndUpdate(t *testing.T) {
|
||||||
name, name2, new_name := "update", "update2", "new_update"
|
name, name2, new_name := "update", "update2", "new_update"
|
||||||
user := User{Name: name, Age: 1, PasswordHash: []byte{'f', 'a', 'k', '4'}}
|
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)
|
db.Save(&user)
|
||||||
if user.Id == 0 {
|
if user.Id == 0 {
|
||||||
t.Errorf("Should have ID after create")
|
t.Errorf("Should have ID after create")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if db.NewRecord(user) {
|
||||||
|
t.Error("User should not new record after save")
|
||||||
|
}
|
||||||
|
|
||||||
var u User
|
var u User
|
||||||
db.First(&u, user.Id)
|
db.First(&u, user.Id)
|
||||||
if !reflect.DeepEqual(u.PasswordHash, []byte{'f', 'a', 'k', '4'}) {
|
if !reflect.DeepEqual(u.PasswordHash, []byte{'f', 'a', 'k', '4'}) {
|
||||||
|
|
4
main.go
4
main.go
|
@ -238,6 +238,10 @@ func (s *DB) Rollback() *DB {
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *DB) NewRecord(value interface{}) bool {
|
||||||
|
return s.clone().do(value).model.primaryKeyZero()
|
||||||
|
}
|
||||||
|
|
||||||
// Migrations
|
// Migrations
|
||||||
func (s *DB) CreateTable(value interface{}) *DB {
|
func (s *DB) CreateTable(value interface{}) *DB {
|
||||||
return s.clone().do(value).createTable().db
|
return s.clone().do(value).createTable().db
|
||||||
|
|
Loading…
Reference in New Issue