"doesn't have relation" from go-pg

362 Views Asked by At

I am trying to pull data for CountyEntity that related with 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"`
}

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"

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?

1

There are 1 best solutions below

0
On

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

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. You can find more information about all of these here: https://pg.uptrace.dev/models/