简体   繁体   English

go-pg 中的“没有关系”

[英]“doesn't have relation” from go-pg

I am trying to pull data for CountyEntity that related with CityEntity:我正在尝试提取与 CityEntity 相关的 CountyEntity 数据:

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

My query is:我的查询是:

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

it throws that:它抛出:

model=CountyEntity does not have relation="City" model=CountyEntity 没有关系=“City”

But actually, I have the relation between city and county table on the database.但实际上,我在数据库中有城市和县表之间的关系。

Db Relation Image数据库关系图

I tried different ways to solve but I couldn't solve it.我尝试了不同的方法来解决,但我无法解决。 Does anybody have an idea about what is the root cause of it and what is the possible solutions?有没有人知道它的根本原因是什么以及可能的解决方案是什么?

Pretty old and I'm sure you've figured it out by now, but for anyone else that stumbles across this your model should look like this很老了,我相信你现在已经弄清楚了,但是对于其他偶然发现这个的人来说,你的 model 应该看起来像这样

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

Notice the "rel:has-one" added to the city column.注意添加到城市列的“rel:has-one”。 You can find more information about all of these here: https://pg.uptrace.dev/models/您可以在此处找到有关所有这些的更多信息: https://pg.uptrace.dev/models/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM