Column in latest go-pg

738 Views Asked by At

I am updating from go-pg from 8.0.5 to 10.3.2 and I am having a problem with the columns ORM

structures:

type Item struct {
    ID   int    `pg:"id,pk"`
    Name string `pg:"name"`
    Desc string `pg:"description"`

    SubItems []SubItem `pg:"rel:has-many"`
}

type SubItem struct {
    ID     int    `pg:"id,pk"`
    ItemID int    `pg:"item_id"`
    Name   string `pg:"name"`

    Item Item `pg:"rel:has-one"`
}

and this is the section of the unit test that is failing

list := []test.Item{{ID: 1, Name: "first"}, {ID: 2, Name: "second"}, {ID: 3, Name: "third"}}
subItems := []test.SubItem{{ID: 1, ItemID: 1}, {ID: 2, ItemID: 3}}

_, err := dbConn.model(list).Insert()
So(err, ShouldBeNil)
_, err = dbConn.model(subItems).Insert()
So(err, ShouldBeNil)

expected := test.SubItem{
    ID:     2,
    ItemID: 3,
    Item:   test.Item{ID: 3, Name: "third"},
}

var actual test.SubItem

err = dbConn.Model(&actual).Column("item").Where("sub_item.id = 2").Select()
So(err, ShouldBeNil)
So(actual, ShouldResemble, expected)

The problem I am running into is, in v8, this selected item with a join. In v10, it's throwing a "column 'item' does not exist" error.
What is the correct way of doing this?

1

There are 1 best solutions below

0
On BEST ANSWER

It is changed in v9 check changes here:

Query.Column does not accept relation name any more. Use Query.Relation instead which returns an error if relation does not exist.

Try with Relation then you get all the Item columns.

err = dbConn.Model(&actual).
    Column("_").
    Relation("Item").
    Where("sub_item.id = 2").
    Select()

There are more select options with mappings of table relations in docs: Writing queries