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

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

reply all(3)
阿神

beego's ORM should use id int as the primary key by default

There must be a primary key when reading, updating, and deleting. It should only be required when creating, because the primary key is auto. Your primary key setting is correct

Uid int `orm:"pk"`

In fact, it is recommended that the primary key is like this

Id int

Then when this code, such as read, beego orm is executed, it will find the primary key, get the value of the primary key, and then execute
select fields from user where uid = value, your If the value of the primary key does not exist (0), the ORM cannot execute the select, and of course an error will be reported

 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...

I feel this ORM is more useful.

阿神

By first querying, find out whether the changed primary key has a value Read()
Insert Update Delete

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template