首页 文章

Gorm中不同表名的一对一关系

提问于
浏览
1

我有以下表格 .

nyct2010
enter image description here

trips

enter image description here

我定义的模型如下 .

type Nyct2010 struct {
    Id      int `gorm:"column:gid"`
    Borocode int
}

type Trip struct {
    Id               int
    PickupLongitude  float64   `gorm:"column:pickup_longitude"`
    PickupLatitude   float64   `gorm:"column:pickup_latitude"`
    DropoffLongitude float64   `gorm:"column:dropoff_longitude"`
    DropoffLatitude  float64   `gorm:"column:dropoff_latitude"`
    PickupTime       time.Time `gorm:"column:pickup_datetime"`
    DropoffTime      time.Time `gorm:"column:dropoff_datetime"`
    Fare             float64   `gorm:"column:fare_amount"`
    Tip              float64   `gorm:"column:tip_amount"`
    Total            float64   `gorm:"column:total_amount"`
    PaymentType      string    `gorm:"column:payment_type"`
    Tax              float64   `gorm:"column:mta_tax"`

    Nyct2010   Nyct2010
    Nyct2010Id int `gorm:"column:pickup_nyct2010_gid"`
}

我想从 nyct2010 获取相关条目 . 它与 pickup_nyc2010_gid 有关 .

var trip Trip
db.First(&trip, 2112111736)

db.Model(trip).Related(&trip.Nyct2010)

上面的代码生成以下调试消息 .

[2016-01-15 12:34:04]  [160.31ms]  SELECT  * FROM "trips"  WHERE ("id" = '2112111736') ORDER BY "trips"."id" ASC LIMIT 1

[2016-01-15 12:34:04]  pq: zero-length delimited identifier at or near """" 

[2016-01-15 12:34:04]  [77.29ms]  SELECT  * FROM "nyct2010"  WHERE ("" = '1475')

[2016-01-15 12:34:04]  pq: zero-length delimited identifier at or near """"

出于某种原因,gorm忽略了我正在映射 Nyct2010.Id 的字段,我试图将其映射到 Nyct2010.gid .

我是不是错了,或者这是Gorm的错误?

1 回答

  • 0

    试试这个:

    type Nyct2010 struct {
        ID        uint `gorm:"primary_key column:gid"`
        Borocode  int
    }
    
    var trip Trip
    var nyct2010 Nyct2010
    
    db.First(&trip, 2112111736)
    db.Model(&trip).Related(&nyct2010,"pickup_nyct2010_gid")
    

相关问题