6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Beego を触ってみる (Model)

Last updated at Posted at 2014-09-07

データベース接続の設定を行う

main.go にデータベース接続設定を追記する。

package main

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	_ "github.com/macococo/sample/routers"
)

func init() {
	initDb()
}

func initDb() {
	orm.RegisterDriver("mysql", orm.DR_MySQL)
	orm.RegisterDataBase("default", "mysql", "hoge:hoge@tcp(127.0.0.1:3306)/hoge?charset=utf8")
	orm.SetMaxIdleConns("default", 100)
	orm.SetMaxOpenConns("default", 100)

	err := orm.RunSyncdb("default", false, true)
	if err != nil {
		panic(err)
	}
}

func main() {
	beego.Run()
}

Model を追記する

サンプルとしてユーザー情報を表す Usermodels/user.go に追加してみる。
User を CRUD 操作する UserManager も一緒に記述する。
t_user という記述がベタになってしまうのがダサいのだが、実テーブル名をどう取れば良いかわからなかった。

package models

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

type ModelManager struct {
	o orm.Ormer
}

func (this *ModelManager) GetOrm() orm.Ormer {
	if this.o == nil {
		this.o = orm.NewOrm()
	}
	return this.o
}

type User struct {
	Id   int
	Name string
}

type UserManager struct {
	ModelManager
}

func init() {
	orm.RegisterModelWithPrefix("t_", new(User))
}

func (this *UserManager) All() []*User {
	o := this.GetOrm()

	var users []*User
	_, err := o.QueryTable("t_user").All(&users)
	if err != nil {
		beego.Error(err)
	}

	return users
}

func (this *UserManager) Count() int64 {
	o := this.GetOrm()

	cnt, err := o.QueryTable("t_user").Count()
	if err != nil {
		beego.Error(err)
	}

	return cnt
}
func (this *UserManager) Create(user *User) *User {
	o := this.GetOrm()

	_, err := o.Insert(user)
	if err != nil {
		beego.Error(err)
		return nil
	}

	return user
}

func (this *UserManager) Update(user *User) *User {
	o := this.GetOrm()

	_, err := o.Update(user)
	if err != nil {
		beego.Error(err)
		return nil
	}

	return user
}

Controller から Model を操作してみる

ユーザー一覧を取得して JSON で返してみる。

package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/macococo/sample/models"
)

type UserListController struct {
	beego.Controller
}

func (this * UserListController) Get() {
	if !exist {
	userManager := models.UserManager{}
	users := userManager.All()

	content, err := json.Marshal(&users)
	if err != nil {
		beego.Error(err)
	}

	this.Ctx.Output.Body(content)
}
6
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?