英文:
beego models registered but not found
问题
我正在尝试编写我的第一个beego web应用程序,并尝试注册一些模型。我在models/model.go
的init()
函数中注册它们,但是当我运行bee run
命令时,出现以下错误:
no Model found, need register your model
main.go:
package main
import (
"fmt"
_ "test_blog/routers"
"time"
_ "github.com/lib/pq"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
)
func init() {
orm.RegisterDriver("postgres", orm.DRPostgres)
maxIdle := 30
maxConn := 30
orm.RegisterDataBase(
"default",
"postgres",
"postgres://user:password@localhost/test_db", maxIdle, maxConn
)
orm.DefaultTimeLoc = time.UTC
}
func main() {
// Database alias.
name := "default"
// Drop table and re-create.
force := false
// Print log.
verbose := false
// Error.
err := orm.RunSyncdb(name, force, verbose)
if err != nil {
fmt.Println(err)
}
beego.Run()
}
注意: 在第一次运行bee run
之前,force
和verbose
都被设置为true
。
models.go:
package main
import "github.com/astaxie/beego/orm"
type User struct {
Name string
Posts []*Post `orm:"reverse(many)"`
}
type Post struct {
Title string `orm:"size(50)"`
Text string `orm:"size(4000)"`
Created time.Time `orm:"auto_now_add;type(datetime)"`
Updated time.Time `orm:"auto_now;type(datetime)"`
Author *User `orm:"rel(fk)"`
}
func init() {
orm.RegisterModel(new(User), new(Post))
}
英文:
I'm trying to write my first beego web app and I'm trying to register some models, i register them in models/model.go
's init()
function, but when I run the command bee run
, I get the following error:
no Model found, need register your model
main.go:
package main
import (
"fmt"
_ "test_blog/routers"
"time"
_ "github.com/lib/pq"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
)
func init() {
orm.RegisterDriver("postgres", orm.DRPostgres)
maxIdle := 30
maxConn := 30
orm.RegisterDataBase(
"default",
"postgres",
"postgres://user:password@localhost/test_db", maxIdle, maxConn
)
orm.DefaultTimeLoc = time.UTC
}
func main() {
// Database alias.
name := "default"
// Drop table and re-create.
force := false
// Print log.
verbose := false
// Error.
err := orm.RunSyncdb(name, force, verbose)
if err != nil {
fmt.Println(err)
}
beego.Run()
}
Note: force
& verbose
both were set to true
before running bee run
for the first time.
models.go:
package main
import "github.com/astaxie/beego/orm"
type User struct {
Name string
Posts []*Post `orm:"reverse(many)"`
}
type Post struct {
Title string `orm:"size(50)"`
Text string `orm:"size(4000)"`
Created time.Time `orm:"auto_now_add;type(datetime)"`
Updated time.Time `orm:"auto_now;type(datetime)"`
Author *User `orm:"rel(fk)"`
}
func init() {
orm.RegisterModel(new(User), new(Post))
}
答案1
得分: 4
请尝试以下操作:
- 在models.go中,将
package main
改为package models
- 在main.go中,添加
import _ "test_blog/models"
英文:
try this:
- in models.go, change
package main
topackage models
- in main.go, add
import _ "test_blog/models"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论