英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论