首页 >> Golang >> 内容页

Beego框架m2m关联中间表模型怎么自定义?

对于beego框架的orm,教程、文档上面的描述、例子不详尽。尽管上面又多对多模型的定义例子,但是那是对于新项目而言的,如果有那么个情况,是需要在现有的数据库(包含数据)的情况下开发,可能,文档上的例子就不能直接搬了。而在找了很多网页之后, 最终在beego框架本身的代码里面找到了例子。

github.com\astaxie\beego\orm\models_test.go

多对多关系,会需要有一个中间表来保存,两个模型之间关联,比如Post和Tag,中间可能就得有个posts_tags_relations的表来保存两者的关联关系。
Post :

//PostModel
type Post struct {
Id          int64
Title       string orm:size(255)
Content     string orm:"type(text)"
Published   bool
CreatedAt   time.Time orm:type(datetime)
Cat         Category orm:"rel(fk)"
Tags        []Tag    orm:"rel(m2m);rel_through(goblog/models.PostTagRelation)"
}

Tag:

type Tag struct {
    Id  int64
    Name string `orm:size(255);unique`
    Posts []*Post `orm:"reverse(many)"`
}

两者关系模型:

type PostTagRelation struct {
    Id   int64 `orm:-`
    Post *Post `orm: "rel(fk) "`
    Tag  *Tag  `orm: "rel(fk) "`
}

func (m *PostTagRelation) TableName() string {
    return  "posts_tags_relations "
}

看样子跟Beego自动生成的没有什么区别, 但为什么要自己定义??
原因是,之前的数据库表名问题, 不自定义rel_through, Beego找不到这个中间表