1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-22 20:30:55 +00:00
Beego/orm/docs/zh/Object.md

60 lines
1.1 KiB
Markdown
Raw Normal View History

2013-08-08 03:07:08 +00:00
## 对象的CRUD操作
2013-07-31 14:11:35 +00:00
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()
2013-08-19 14:37:53 +00:00
user := new(User)
2013-08-08 03:07:08 +00:00
user.Name = "slene"
2013-08-01 07:52:05 +00:00
fmt.Println(o.Insert(user))
2013-08-08 03:07:08 +00:00
user.Name = "Your"
2013-08-01 07:52:05 +00:00
fmt.Println(o.Update(user))
2013-08-07 11:11:57 +00:00
fmt.Println(o.Read(user))
2013-08-01 07:52:05 +00:00
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}
err = o.Read(&user)
2013-08-01 07:52:05 +00:00
if err == sql.ErrNoRows {
fmt.Println("查询不到")
} else if err == orm.ErrMissPK {
fmt.Println("找不到主键")
} else {
2013-08-08 03:07:08 +00:00
fmt.Println(user.Id, user.Name)
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-08 03:07:08 +00:00
user.Name = "slene"
2013-08-01 01:23:44 +00:00
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 {
2013-08-08 03:07:08 +00:00
user.Name = "MyName"
2013-08-01 07:52:05 +00:00
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 的值