beego orm join 聯合查詢的問題

kggg發表於2017-09-05

下面程式碼中想通過表 blogs 查詢文章列表, 現在有一個問題是在 blogs 明明加了 Users, 但是每次查詢都顯示沒有定義, 怎麼回事?  將 blogs 中 users 註釋掉, 可以正常查詢到 blog.Category.Category

[test@test orm]$ go run orm.go

command-line-arguments

./orm.go:74: blogs.Users undefined (type [] Blogs has no field or method Users)

package main

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


func init() {
        orm.RegisterDriver("mysql", orm.DRMySQL)
        orm.RegisterDataBase("default", "mysql", "root:@/blog?charset=utf8")
}

type Users struct {
    Id          int
    Name        string
    Email       string
    Password      string
    Remember_token string
    Created_at  string
    updated_at  string
    //Blogs  []*Blogs `orm:"reverse(many)"`
}

type Subject struct {
        Id      int
        User_id  int
        Subject  string
        create_at string
        //Blogs  []*Blogs `orm:"reverse(many)"`
}

type Category struct {
        Id  int
        User_id  int
        Subject_id  int
        Category  string
        created_at string
        //Blogs  []*Blogs  `orm:"reverse(many)"`
}

type Blogs struct {
        Id  int   `pk:"auto"`
        Users  *Users    `orm:"rel(fk)"`
        Subject  *Subject   `orm:"rel(fk)"`
        Category  *Category   `orm:"rel(fk)"`
        Title   string
        Content   string
        Created_at  string
        Updated_at  string

}

func init() {
    orm.RegisterModel(new(Users), new(Subject), new(Blogs), new(Category))
}

func main(){
    o := orm.NewOrm()
    var blog []Blogs
    o.QueryTable("blogs").Filter("Id", 168).RelatedSel().All(&blog)
    for _, v := range blog {
         //fmt.Println(v.Category.Category)
        fmt.Println(v.Users.Name)
    }
/*
    FindBlogs(2)
*/
}


更多原創文章乾貨分享,請關注公眾號
  • beego orm join 聯合查詢的問題
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章