"go
package main
import (
"fmt"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
"time"
)
type Userinfo struct {
Uid int `orm:"pk"`
Username string
Departname string
Created time.Time
}
func init() {
orm.RegisterModel(new(Userinfo))
orm.RegisterDataBase("default", "mysql", "momaek:123456@/test?charset=utf8")
}
func main() {
o := orm.NewOrm()
user := Userinfo{Username: "hello", Departname: "wd"}
id, err := o.Insert(&user)
fmt.Printf("ID:%d, Err: %v\n ", id, err)
user.Uid = 3
user.Created = time.Now()
user.Departname = "wakkkk"
num, err := o.Update(&user)
fmt.Printf("Num:%d ,ERR: %v\n", num, err)
u := Userinfo{Username: "hello"}
err = o.Read(&u)
fmt.Println(u)
fmt.Printf("ERR: %v\n", err)
num, err = o.Delete(&u)
fmt.Printf("NUM: %d, Err: %v\n", num, err)
}
"
代码是这样的。然后运行报错:
ID:47, Err: <nil>
Num:0 ,ERR: <nil>
{0 hello 0001-01-01 00:00:00 +0000 UTC}
ERR: missed pk value
NUM: 0, Err: missed pk value
阿神2017-04-17 11:17:39
beego的orm預設應該把id int
當作主鍵
read, update, delete的時候必須有主鍵,應該只有create的時候不需要,因為主鍵是auto的。你主鍵設定是正確的
Uid int `orm:"pk"`
其實建議主鍵是這樣的
Id int
然後這段程式碼,例如read,beego orm 執行的時候,會找到主鍵,取得主鍵的值value,然後執行select fields from user where uid = value
,你的主鍵的值不存在(0),orm就沒辦法執行select, 當然會報錯
u := Userinfo{Username: "hello"}
err = o.Read(&u)
fmt.Println(u)
fmt.Printf("ERR: %v\n", err)
num, err = o.Delete(&u)
fmt.Printf("NUM: %d, Err: %v\n", num, err)