beego 多对多查询报错
本人最近在学习beego框架,正用一个博客练手,文章这部分遇到了一些问题,我google了半天,发现我的语法好像没什么问题,但是就是报错,希望各位大佬给看一看多谢!
一篇文章可以有多个label
,而一个label
也可以被多篇文章使用,所以使用了多对多的模型关系
下面是文章Article
模型
type Article struct {
Id int `form:"-"`
//这个是标签
Label []*Label `orm:"rel(m2m);rel_through(blog/models.Articlelabel)"`
}
这个是标签Label
模型
type Label struct {
Id int `form:"-"`
Title string `form:"title"`
//这个是文章关联
Article []*Article `orm:"reverse(many)"`
}
这个是关联模型Articlelabel
type Articlelabel struct {
Id int
Article_id *Article `orm:"rel(fk)"`
Label_id *Label `orm:"rel(fk)"`
}
查询的代码
var list []Article
o := orm.NewOrm()
_, err := o.QueryTable("article").RelatedSel().Limit(10).All(&list)
if err != nil {
return []Article{}, err
}
for _,v := range list {
//这里打印 V是可以打印出来的
//加上这句就报错
o.LoadRelated(v, "Label")
}
return list, nil
加上这句o.LoadRelated(v, "Label")
就报错,不知道是我哪里出了问题
报错如下
2020/03/01 18:54:29.795 [C] [panic.go:679] the request url is /admin/article
2020/03/01 18:54:29.795 [C] [panic.go:679] Handler crashed with error <Ormer> cannot use non-ptr model struct `blog/models.Article`
2020/03/01 18:54:29.796 [C] [panic.go:679] D:/Go/src/runtime/panic.go:679
2020/03/01 18:54:29.796 [C] [panic.go:679] F:/go_workspace/go/src/github.com/astaxie/beego/orm/orm.go:108
2020/03/01 18:54:29.818 [C] [panic.go:679] F:/go_workspace/go/src/github.com/astaxie/beego/orm/orm.go:352
2020/03/01 18:54:29.821 [C] [panic.go:679] F:/go_workspace/go/src/github.com/astaxie/beego/orm/orm.go:278
2020/03/01 18:54:29.822 [C] [panic.go:679] F:/go_workspace/go/src/blog/models/article.go:38
2020/03/01 18:54:29.823 [C] [panic.go:679] F:/go_workspace/go/src/blog/controllers/admin/article.go:22
2020/03/01 18:54:29.823 [C] [panic.go:679] F:/go_workspace/go/src/github.com/astaxie/beego/router.go:833
2020/03/01 18:54:29.824 [C] [panic.go:679] D:/Go/src/net/http/server.go:2802
2020/03/01 18:54:29.825 [C] [panic.go:679] D:/Go/src/net/http/server.go:1890
2020/03/01 18:54:29.825 [C] [panic.go:679] D:/Go/src/runtime/asm_amd64.s:1357
2020/03/01 18:54:29.826 [server.go:3053] [HTTP] http: superfluous response.WriteHeader call from github.com/astaxie/beego/context.(*Response).WriteHeader (context.go:230)
查询了网上的文章大多是一个文章各种抄,没办法只能来提问了。提前感谢
找到原因了,因为list 在循环的时候v并不是结构体的引用,我看文档都是用引用的,所以改成引用,而循环中的v地址和原数据地址是不一样的所以要改成
&list[k]
贴一下代码