How get data from database in Go&Beego?

huangapple go评论79阅读模式
英文:

How get data from database in Go&Beego?

问题

我尝试在Go和Beego上创建一个简单的REST服务。

我无法理解Beego的逻辑。

所有的示例都只提供了如何检索单个项目的信息,而我需要获取所有项目的信息。

在API的情况下。

控制器:

package controllers
import (
    "api/models"
    "github.com/astaxie/beego"
)

type UserController struct {
    beego.Controller
}

func (u *UserController) GetAll() {
    users := models.GetAllUsers()
    u.Data["json"] = users
    u.ServeJSON()
}

模型:

package models

import (
    "github.com/astaxie/beego/orm"
)

var (
    UserList map[int]*User
)

func init() {
    orm.RegisterModel(new(User))

    UserList = make(map[int]*User)

    u := User{1, "Chandler", "Bing", "chandlerbing@gmail.com"}
    UserList[1] = &u
}

type User struct {
    Id         int    `form:"id"`
    First_name string `form:"first_name"`
    Last_name  string `form:"last_name"`
    Email      string `form:"email"`
}

func GetAllUsers() map[int]*User {
    return UserList
}

这样可以工作!但是,我如何从数据库获取数据?

数据库连接正常(MySQL)

英文:

I try create a simple REST service on Go&Beego.

I can not understand the logic of Beego.

All examples have information on how to retrieve just one item while I need to get all items.

In case of API.

Controller:

package controllers
import (
	"api/models"
	"github.com/astaxie/beego"
)

type UserController struct {
	beego.Controller
}

func (u *UserController) GetAll() {
	users := models.GetAllUsers()
	u.Data["json"] = users
	u.ServeJSON()
}

Model:

package models

import (
	"github.com/astaxie/beego/orm"
)

var (
	UserList map[int]*User
)

func init() {
	orm.RegisterModel(new(User))

	UserList = make(map[int]*User)

	u := User{1, "Chandler", "Bing", "chandlerbing@gmail.com"}
	UserList[1] = &u
}

type User struct {
	Id int `form:"id"`
	First_name string `form:"first_name"`
	Last_name string `form:"last_name"`
	Email string `form:"email"`
}

func GetAllUsers() map[int]*User {
	return UserList
}

That works! But, how can I get data from database?

Database connections are ok (MySQL)

答案1

得分: 1

你应该按照这里提到的使用QueryTable

var users []*User
num, err := o.QueryTable("user").Filter("name", "slene").All(&users)

在你的情况下,你的GetAllUsers应该像这样,但我没有测试过。

func GetAllUsers() map[int]*User {
    usrs, err := orm.QueryTable("users").Values(&UserList)
    if err != nil {
        panic(err)
    }
    return UserList
}
英文:

You should use QueryTable as mentioned here

var users []*User
num, err := o.QueryTable("user").Filter("name", "slene").All(&users)

In your case your GetAllUsers should look like this but I didn't tested it.

func GetAllUsers() map[int]*User {
    usrs, err := orm.QueryTable("users").Values(&UserList)
    if err != nil {
        panic(err)
    }
    return UserList
}

huangapple
  • 本文由 发表于 2017年9月11日 22:24:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/46158034.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定