簡體   English   中英

go-pg 中的“沒有關系”

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

我正在嘗試提取與 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"`
}

我的查詢是:

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”

但實際上,我在數據庫中有城市和縣表之間的關系。

數據庫關系圖

我嘗試了不同的方法來解決,但我無法解決。 有沒有人知道它的根本原因是什么以及可能的解決方案是什么?

很老了,我相信你現在已經弄清楚了,但是對於其他偶然發現這個的人來說,你的 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"`
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM