Return query error in FirstOrInit and FirstOrCreate

This commit is contained in:
Jinzhu 2014-06-23 20:10:50 +08:00
parent a89500c855
commit 6c5b95e2b2
1 changed files with 10 additions and 2 deletions

12
main.go
View File

@ -165,7 +165,11 @@ func (s *DB) Scan(dest interface{}) *DB {
func (s *DB) FirstOrInit(out interface{}, where ...interface{}) *DB { func (s *DB) FirstOrInit(out interface{}, where ...interface{}) *DB {
c := s.clone() c := s.clone()
if c.First(out, where...).Error == RecordNotFound { r := c.First(out, where...)
if r.Error != nil {
if !r.RecordNotFound() {
return r
}
c.NewScope(out).inlineCondition(where...).initialize() c.NewScope(out).inlineCondition(where...).initialize()
} else { } else {
c.NewScope(out).updatedAttrsWithValues(convertInterfaceToMap(s.search.AssignAttrs), false) c.NewScope(out).updatedAttrsWithValues(convertInterfaceToMap(s.search.AssignAttrs), false)
@ -175,7 +179,11 @@ func (s *DB) FirstOrInit(out interface{}, where ...interface{}) *DB {
func (s *DB) FirstOrCreate(out interface{}, where ...interface{}) *DB { func (s *DB) FirstOrCreate(out interface{}, where ...interface{}) *DB {
c := s.clone() c := s.clone()
if c.First(out, where...).Error == RecordNotFound { r := c.First(out, where...)
if r.Error != nil {
if !r.RecordNotFound() {
return r
}
c.NewScope(out).inlineCondition(where...).initialize().callCallbacks(s.parent.callback.creates) c.NewScope(out).inlineCondition(where...).initialize().callCallbacks(s.parent.callback.creates)
} else if len(s.search.AssignAttrs) > 0 { } else if len(s.search.AssignAttrs) > 0 {
c.NewScope(out).Set("gorm:update_interface", s.search.AssignAttrs).callCallbacks(s.parent.callback.updates) c.NewScope(out).Set("gorm:update_interface", s.search.AssignAttrs).callCallbacks(s.parent.callback.updates)