beego的CRUD操作

2023-11-20 18:07 更新

對象的 CRUD 操作

如果已知主鍵的值,那么可以使用這些方法進行 CRUD 操作

對 object 操作的四個方法 Read / Insert / Update / Delete

o := orm.NewOrm()
user := new(User)
user.Name = "slene"

fmt.Println(o.Insert(user))

user.Name = "Your"
fmt.Println(o.Update(user))
fmt.Println(o.Read(user))
fmt.Println(o.Delete(user))

如果需要通過條件查詢獲取對象,請參見高級查詢

Read

o := orm.NewOrm()
user := User{Id: 1}

err := o.Read(&user)

if err == orm.ErrNoRows {
    fmt.Println("查詢不到")
} else if err == orm.ErrMissPK {
    fmt.Println("找不到主鍵")
} else {
    fmt.Println(user.Id, user.Name)
}

Read 默認通過查詢主鍵賦值,可以使用指定的字段進行查詢:

user := User{Name: "slene"}
err = o.Read(&user, "Name")
...

對象的其他字段值將會是對應(yīng)類型的默認值

復(fù)雜的單個對象查詢參見 One

ReadOrCreate

嘗試從數(shù)據(jù)庫讀取,不存在的話就創(chuàng)建一個

默認必須傳入一個參數(shù)作為條件字段,同時也支持多個參數(shù)多個條件字段

o := orm.NewOrm()
user := User{Name: "slene"}
// 三個返回參數(shù)依次為:是否新創(chuàng)建的,對象 Id 值,錯誤
if created, id, err := o.ReadOrCreate(&user, "Name"); err == nil {
    if created {
        fmt.Println("New Insert an object. Id:", id)
    } else {
        fmt.Println("Get an object. Id:", id)
    }
}

Insert

第一個返回值為自增健 Id 的值

o := orm.NewOrm()
var user User
user.Name = "slene"
user.IsActive = true

id, err := o.Insert(&user)
if err == nil {
    fmt.Println(id)
}

創(chuàng)建后會自動對 auto 的 field 賦值

InsertMulti

同時插入多個對象

類似sql語句

insert into table (name, age) values("slene", 28),("astaxie", 30),("unknown", 20)

第一個參數(shù) bulk 為并列插入的數(shù)量,第二個為對象的slice

返回值為成功插入的數(shù)量

users := []User{
    {Name: "slene"},
    {Name: "astaxie"},
    {Name: "unknown"},
    ...
}
successNums, err := o.InsertMulti(100, users)

bulk 為 1 時,將會順序插入 slice 中的數(shù)據(jù)

Update

第一個返回值為影響的行數(shù)

o := orm.NewOrm()
user := User{Id: 1}
if o.Read(&user) == nil {
    user.Name = "MyName"
    if num, err := o.Update(&user); err == nil {
        fmt.Println(num)
    }
}

Update 默認更新所有的字段,可以更新指定的字段:

// 只更新 Name
o.Update(&user, "Name")
// 指定多個字段
// o.Update(&user, "Field1", "Field2", ...)
...

根據(jù)復(fù)雜條件更新字段值參見 Update

Delete

第一個返回值為影響的行數(shù)

o := orm.NewOrm()
if num, err := o.Delete(&User{Id: 1}); err == nil {
    fmt.Println(num)
}

Delete 操作會對反向關(guān)系進行操作,此例中 Post 擁有一個到 User 的外鍵。刪除 User 的時候。如果 on_delete 設(shè)置為默認的級聯(lián)操作,將刪除對應(yīng)的 Post

Changed in 1.0.3 刪除以后不會刪除 auto field 的值

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號