# GORM - CB

## 1.1 Create

```go
// begin transaction
BeforeSave
BeforeCreate
// save before-associations
// update timestamp `CreatedAt`, `UpdatedAt`
// save self
// reload fields that have default value and its value is blank
// save after-associations
AfterCreate
AfterSave
// commit or rollback transaction
```

## 1.2 Update

```go
// begin transaction
BeforeSave
BeforeUpdate
// save before-associations
// update timestamp `UpdatedAt`
// save self
// save after-associations
AfterUpdate
AfterSave
// commit or rollback transaction
```

## 1.3 Delete

```go
// begin transaction
BeforeDelete
// delete self
AfterDelete
// commit or rollback transaction
```

## 1.4 Find

```go
// load data from database
// Preloading (edger loading)
AfterFind
```

## 2. Example

```go
func (u *User) BeforeUpdate() (err error) {
    if u.readonly() {
        err = errors.New("read only user")
    }
    return
}

func (u *User) AfterCreate() (err error) {
    if (u.Id > 1000) {
        err = errors.New("user id is already greater than 1000")
    }
    return
}
```

change during crud

```go
func (u *User) AfterCreate(tx *gorm.DB) (err error) {
    tx.Model(u).Update("role", "admin")
    return
}
```

```go
func (u *User) AfterCreate(scope *gorm.Scope) (err error) {
  scope.DB().Model(u).Update("role", "admin")
    return
}
```
