0

我正在从 go-pg from 8.0.5to更新10.3.2,我的 ORM 列有问题

结构:

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"`
}

这是单元测试失败的部分

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)

我遇到的问题是,在 v8 中,这item是通过连接选择的。在 v10 中,它会抛出“列 'item' 不存在”错误。
这样做的正确方法是什么?

4

1 回答 1

1

它在 v9 中进行了更改,请在此处检查更改

Query.Column 不再接受关系名称。使用 Query.Relation 代替,如果关系不存在则返回错误。

尝试使用Relation ,然后您将获得所有 Item 列。

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

文档中的表关系映射有更多选择选项:编写查询

于 2020-11-20T17:38:48.033 回答