【问题标题】:"doesn't have relation" from go-pggo-pg 中的“没有关系”
【发布时间】:2020-12-08 15:04:06
【问题描述】:

我正在尝试为 CountyEntity 提取与 CityEntity 相关的数据:

type CityEntity struct {
    tableName struct{} `pg:"city,alias:ci,discard_unknown_columns"`
    Id        string   `pg:"id"`
    Name      string   `pg:"name"`
}

type CountyEntity struct {
    tableName            struct{}    `pg:"county,alias:co,discard_unknown_columns"`
    Id                   int64       `pg:"id"`
    Name                 string      `pg:"name"`
    DefaultTargetXDockId int64       `pg:"defaulttargetxdockid"`
    MapsPreference       string      `pg:"mapspreference"`
    EmptyDistrictAllowed bool        `pg:"empty_district_allowed"`
    CityId               int64       `pg:"cityid"`
    City                 *CityEntity `pg:"fk:cityid"`
}

我的查询是:

db, _ := repository.pgRepository.CreateDBConnection(.....)

var counties []model.CountyEntity
err := db.Model(&counties).
    Join("inner join test.city ci on ci.id = co.cityid").
    Relation("City").
    Where("co.cityid = ?", cityId).
    Select()
return counties, err

它抛出:

model=CountyEntity 没有关系="City"

但实际上,我在数据库中有城市和县表之间的关系。

Db Relation Image

我尝试了不同的方法来解决,但我无法解决。有没有人知道它的根本原因是什么以及可能的解决方案是什么?

【问题讨论】:

    标签: go go-pg


    【解决方案1】:

    相当老了,我相信你现在已经弄明白了,但是对于其他偶然发现这个的人来说,你的模型应该是这样的

    type CountyEntity struct {
        tableName            struct{}    `pg:"county,alias:co,discard_unknown_columns"`
        Id                   int64       `pg:"id"`
        Name                 string      `pg:"name"`
        DefaultTargetXDockId int64       `pg:"defaulttargetxdockid"`
        MapsPreference       string      `pg:"mapspreference"`
        EmptyDistrictAllowed bool        `pg:"empty_district_allowed"`
        CityId               int64       `pg:"cityid"`
        City                 *CityEntity `pg:"rel:has-one,fk:cityid"`
    }
    

    请注意添加到城市列的“rel:has-one”。您可以在此处找到有关所有这些的更多信息:https://pg.uptrace.dev/models/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 2014-05-07
      相关资源
      最近更新 更多