1. 程式人生 > >Beego框架:orm使用

Beego框架:orm使用

使用者結構體,和訂單是一對多的關係

type User struct {
	Id int //beego中預設Id為主鍵,且自增長
	Name string //姓名
	Age int //年齡
	Nickname string  //暱稱
	Userorders []*Userorder `orm:"reverse(many)"`
}

訂單結構體,和使用者是多對多一的關係

type Userorder struct {
	Id int
	Orderdata string
	User *User `orm:"rel(fk)"`
	Products []*Product `orm:"rel(m2m)"`//ManyToMany
}

建立orm物件,插入使用者:

func (this *InsertUserController) Get() {
	this.TplName = "insertuser.html"
}
func (this *InsertUserController) Post() {
	name := this.GetString("name")
	age, err := this.GetInt("age")
	if err != nil {
		this.Ctx.WriteString("插入失敗!")
	}
	nickname := this.GetString("nickname")
	user := models.User{Name:name, Age:age, Nickname:nickname}
	orm := orm.NewOrm()
	//INSERT INTO USER (NAME, age, nickname)  VALUE('Alice', 24, 'bb')
	n, err := orm.Insert(&user)
	if err == nil && n > 0 {
		this.Ctx.WriteString("插入成功!")
	}else {
		this.Ctx.WriteString("插入失敗!")
	}
}

insertuser.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>插入使用者</title>
</head>
<body>
    <form action="/insertuser" method="post">
        <table>
            <thead>插入使用者</thead>
            <tbody>
                <tr>
                    <td>姓名:</td>
                    <td>
                        <input id="name" name="name" type="text">
                    </td>
                </tr>
                <tr>
                    <td>年齡:</td>
                    <td>
                        <input id="age" name="age" type="text">
                    </td>
                </tr>
                <tr>
                    <td>暱稱:</td>
                    <td>
                        <input id="nickname" name="nickname" type="text">
                    </td>
                </tr>
                <tr>
                    <td>
                        <input type="submit" value="插入"/>
                    </td>
                    <td>
                        <input type="reset" value="重置"/>
                    </td>
                </tr>
            </tbody>
        </table>
    </form>
</body>
</html>

刪除使用者

func (this *DeleteUserController) Get1() {
	//通過id刪除
	//http://localhost:8080/deleteuser?id=2
	//獲取id
	id, err := this.GetInt("id")
	if err != nil {
		this.Ctx.WriteString("刪除失敗!")
		return
	}
	//建立user物件
	user := models.User{Id:id}
	orm := orm.NewOrm()
	//delete函式預設根據id進行刪除,也可以根據指定的欄位進行刪除
	//DELETE FROM USER WHERE id = 2;
	n, err := orm.Delete(&user)
	if n > 0 && err == nil {
		this.Ctx.WriteString("刪除成功!")
		return
	}else {
		this.Ctx.WriteString("刪除失敗!")
	}
}

func (this *DeleteUserController) Get() {

	//通過姓名刪除
	//http://localhost:8080/deleteuser?name=admin
	name := this.GetString("name")
	user := models.User{Name:name}

	//建立orm物件
	orm := orm.NewOrm()
	//delete函式預設根據id進行刪除,也可以根據指定的欄位進行刪除
	//DELETE FROM USER WHERE NAME='Alice';
	n, err := orm.Delete(&user, "name")
	if n > 0 && err == nil {
		this.Ctx.WriteString("刪除成功!")
		return
	}else {
		this.Ctx.WriteString("刪除失敗!")
	}
}

查詢使用者

func (this *QueryUserController) Get1() {
	//獲取id查詢使用者
	//http://localhost:8080/queryuser?id=2
	id, err := this.GetInt("id")
	if err != nil {
		this.Ctx.WriteString("查詢出錯!")
		return
	}
	user := models.User{Id:id}

	//建立orm
	orm := orm.NewOrm()
	//預設根據id查詢
	//SELECT * FROM USER WHERE id = 4;
	err = orm.Read(&user)
	if err != nil {
		this.Ctx.WriteString("查詢出錯!")
		return
	}else {
		this.Ctx.WriteString("id = " + strconv.Itoa(user.Id) + "\nname = " +
			user.Name + "\nage = " + strconv.Itoa(user.Age) + "\nnickname = " + user.Nickname)
	}
}


func (this *QueryUserController) Get() {
	//http://localhost:8080/queryuser?name=admin
	//獲取使用者輸入的姓名
	name := this.GetString("name")
	//構造user
	user := models.User{Name:name}
	//建立orm
	orm := orm.NewOrm()
	//根據name查詢使用者,Read函式如果不指定引數
	//SELECT * FROM USER WHERE NAME = '吳俏祥';
	err := orm.Read(&user, "name")
	if err != nil {
		this.Ctx.WriteString("查詢出錯!")
		return
	}else {
		this.Ctx.WriteString("id = " + strconv.Itoa(user.Id) + "\nname = " +
			user.Name + "\nage = " + strconv.Itoa(user.Age) + "\nnickname = " + user.Nickname)
	}
}

更新使用者

//http://localhost:8080/updateuser?id=1&name=tom&nickname=234&age=23
func (this *UpdateUserController) Get1() {
	id, err := this.GetInt("id")//獲取id
	if err != nil {
		this.Ctx.WriteString("更新失敗!")
		return
	}
	name := this.GetString("name")//獲取姓名
	nickname := this.GetString("nickname")//獲取暱稱
	age, err := this.GetInt("age")
	if err != nil {
		this.Ctx.WriteString("更新失敗!")
		return
	}
	user := models.User{Id:id, Name:name, Nickname:nickname, Age:age}
	//UPDATE USER SET NAME = '杜紫維' WHERE id = 1;
	//user := models.User{Id:id, Name:name, Nickname:nickname}
	orm := orm.NewOrm()
	//update函式根據物件的id進行更新,必須指定id
	n, err := orm.Update(&user)
	if n > 0 && err == nil {
		this.Ctx.WriteString("更新成功!")
	}else {
		this.Ctx.WriteString("更新失敗!")
	}
}



//http://localhost:8080/updateuser?id=1&name=tom&nickname=234&age=23
func (this *UpdateUserController) Get() {
	id, err := this.GetInt("id")//獲取id
	if err != nil {
		this.Ctx.WriteString("更新失敗!")
		return
	}
	name := this.GetString("name")//獲取姓名
	nickname := this.GetString("nickname")//獲取暱稱
	age, err := this.GetInt("age")
	if err != nil {
		this.Ctx.WriteString("更新失敗!")
		return
	}
	user := models.User{Id:id, Name:name, Nickname:nickname, Age:age}
	//UPDATE USER SET NAME = '杜紫維' WHERE id = 1;
	//user := models.User{Id:id, Name:name, Nickname:nickname}
	orm := orm.NewOrm()
	//update函式根據指定欄位進行更新,且必須指定id
	n, err := orm.Update(&user, "name")
	if n > 0 && err == nil {
		this.Ctx.WriteString("更新成功!")
	}else {
		this.Ctx.WriteString("更新失敗!")
	}
}

插入訂單

func (this *InserOrderController) Get(){
	//建立orm
	orm := orm.NewOrm()
	//建立訂單
	order := models.Userorder{}
	//對訂單初始化
	order.Orderdata = "this is order123"
	order.User = &models.User{Id:6}
	//如果不指定Id,可以插入成功,但是外來鍵user_id為0
	//order.User = &models.User{Name:"吳俏祥"}
	//插入訂單
	n, err := orm.Insert(&order)
	//判斷是否插入成功
	if n > 0 && err != nil {
		this.Ctx.WriteString("插入失敗!")
		return
	}
	this.Ctx.WriteString("插入成功!")
}

查詢訂單

func (this *QueryOrderController) Get(){
	orm := orm.NewOrm()
	//可以傳遞表名(大小寫無關)和物件名
	qs := orm.QueryTable("Userorder")
	var orders []*models.Userorder
	//SELECT * FROM userorder WHERE user_id = 1;
	order_num, err := qs.Filter("user__id", 1).All(&orders)//user__id=user.id
	if err != nil {
		this.Ctx.WriteString("query order fail!")
		return
	}
	fmt.Println("order_num = ", order_num)
	for _, order := range orders {
		fmt.Println("order = ", order)
	}
	this.Ctx.WriteString("查詢成功!")
}

學院Go語言視訊主頁
https://edu.csdn.net/lecturer/1928

清華團隊帶你實戰區塊鏈開發
掃碼獲取海量視訊及原始碼 QQ群:721929980
在這裡插入圖片描述