How to use RelatedSel() method on beego framework properly

2.4k Views Asked by At

I know this is very basic, but i think the official documentation at [beego website][1]

[1]: http://beego.me/docs/mvc/model/query.md doesn't give clear direction.

I made a RESTful API using beego framework. As it promised, it generates basic CRUD code for my app. The problem is READ method doesn't return all data. By all data I mean data in a table including data from all tables related to it.

this is the output from the generated code (i'm using swagger to call it):

{
  "data": [
    {
      "Id": 1,
      "CustomerId": {
        "Id": 2,
        "Name": "",
        "Phone": "",
        "Email": "",
        "CreatedAt": "0001-01-01T00:00:00Z",
        "UpdatedAt": "0001-01-01T00:00:00Z"
      },
      "Saldo": 2500000,
      "CreatedAt": "2014-12-10T08:10:10+07:00",
      "UpdatedAt": "2014-12-10T08:10:10+07:00"
    }
  ],
  "totals": 1
}

see, it doesn't return the Name, Phone, and Email. so i look into documentation and found this method RelatedSel() but still I have no idea how to use it properly.

here's my code:

func GetAllCustomerSaldo(query map[string]string, fields []string, sortby []string, order []string,
    offset int64, limit int64) (ml []interface{}, err error, totals int64) {
    o := orm.NewOrm()
    qs := o.QueryTable(new(CustomerSaldo))
    qs.RelatedSel("CustomerId__Customers").All(&CustomerSaldo{})
...

after trying many parameter possibilities, i still get this error:

Handler crashed with error unknown model/table name `Customers`

Anyone here have same problem with me? any solution guys?

2

There are 2 best solutions below

0
On

It's not necessery to LoadRelated after RelatedSel - because RelatedSel will automatically get data in one request to db (of course if it's correctly used). LoadRelated - do the same but in additional Requests. When You use RelatedSel, and after That LoadRelated - You will do things twice.

  orm.Debug = true

  o := orm.NewOrm()
  qs := o.QueryTable(&models.MainModel{})

  var req []*models.RelatedModel

  num, err := qs.RelatedSel().All(&req)

  beego.Debug(num)

  if err != nil {
    beego.Error(err)
  }
0
On

I had a slightly different problem, but the solution that I have found can help with this problem too. I foun solution here https://github.com/astaxie/beego/issues/1258

You need to call qs.RelatedSel() without parameters (or with int parameter, that responds about deep of relation selection) and manually call LoadRelated for each record

func GetAllCustomerSaldo(query map[string]string, fields []string, sortby []string, order []string,
    offset int64, limit int64) (ml []interface{}, err error, totals int64) {
    o := orm.NewOrm()
    qs := o.QueryTable(new(CustomerSaldo))
    qs.RelatedSel().All(&CustomerSaldo{})
    ...
}

o := orm.NewOrm()
for _, el := range arr {
   o.LoadRelated(el, "CustomerId")
}

RelatedSel is like LeftOuterJoin