mysql - beego的orm每update,delete,read的时候都要给主键值????
迷茫
迷茫 2017-04-17 11:15:39
0
3
849
"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
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

Antworte allen(3)
阿神

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)
黄舟

http://jinzhu.me/gorm/curd.ht...

感觉这个 orm 更好用一些。

阿神

通过先查询,查找改主键是否有值Read()
Insert Update Delete

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!