2013-07-31 14:11:35 +00:00
|
|
|
## Object
|
|
|
|
|
2013-08-01 07:52:05 +00:00
|
|
|
对 object 操作简单的三个方法 Read / Insert / Update / Delete
|
2013-08-01 01:23:44 +00:00
|
|
|
```go
|
|
|
|
o := orm.NewOrm()
|
|
|
|
user := NewUser()
|
|
|
|
user.UserName = "slene"
|
|
|
|
user.Password = "password"
|
|
|
|
user.Email = "vslene@gmail.com"
|
2013-08-01 07:52:05 +00:00
|
|
|
|
|
|
|
fmt.Println(o.Insert(user))
|
|
|
|
|
2013-08-01 01:23:44 +00:00
|
|
|
user.UserName = "Your"
|
2013-08-01 07:52:05 +00:00
|
|
|
fmt.Println(o.Update(user))
|
|
|
|
|
|
|
|
fmt.Println(o.Delete(user))
|
2013-08-01 01:23:44 +00:00
|
|
|
```
|
2013-07-31 14:11:35 +00:00
|
|
|
### Read
|
2013-08-01 01:23:44 +00:00
|
|
|
```go
|
2013-08-01 07:52:05 +00:00
|
|
|
o := orm.NewOrm()
|
|
|
|
user := User{Id: 1}
|
|
|
|
|
|
|
|
o.Read(&user)
|
|
|
|
|
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
fmt.Println("查询不到")
|
|
|
|
} else if err == orm.ErrMissPK {
|
|
|
|
fmt.Println("找不到主键")
|
|
|
|
} else {
|
|
|
|
fmt.Println(user.Id, user.UserName)
|
2013-08-01 01:23:44 +00:00
|
|
|
}
|
|
|
|
```
|
2013-08-01 07:52:05 +00:00
|
|
|
### Insert
|
2013-08-01 01:23:44 +00:00
|
|
|
```go
|
2013-08-01 07:52:05 +00:00
|
|
|
o := orm.NewOrm()
|
|
|
|
var user User
|
2013-08-01 01:23:44 +00:00
|
|
|
user.UserName = "slene"
|
|
|
|
user.Password = "password"
|
|
|
|
user.Email = "vslene@gmail.com"
|
|
|
|
user.IsActive = true
|
|
|
|
|
2013-08-01 07:52:05 +00:00
|
|
|
fmt.Println(o.Insert(&user))
|
2013-08-01 01:23:44 +00:00
|
|
|
fmt.Println(user.Id)
|
|
|
|
```
|
2013-07-31 14:11:35 +00:00
|
|
|
创建后会自动对 auto 的 field 赋值
|
|
|
|
|
|
|
|
### Update
|
2013-08-01 01:23:44 +00:00
|
|
|
```go
|
2013-08-01 07:52:05 +00:00
|
|
|
o := orm.NewOrm()
|
|
|
|
user := User{Id: 1}
|
|
|
|
if o.Read(&user) == nil {
|
|
|
|
user.UserName = "MyName"
|
|
|
|
o.Update(&user)
|
2013-08-01 01:23:44 +00:00
|
|
|
}
|
|
|
|
```
|
2013-07-31 14:11:35 +00:00
|
|
|
### Delete
|
2013-08-01 01:23:44 +00:00
|
|
|
```go
|
2013-08-01 07:52:05 +00:00
|
|
|
o := orm.NewOrm()
|
|
|
|
o.Delete(&User{Id: 1})
|
2013-08-01 01:23:44 +00:00
|
|
|
```
|
2013-07-31 14:11:35 +00:00
|
|
|
Delete 操作会对反向关系进行操作,此例中 Post 拥有一个到 User 的外键。删除 User 的时候。如果 on_delete 设置为默认的级联操作,将删除对应的 Post
|
|
|
|
|
|
|
|
删除以后会清除 auto field 的值
|