【问题标题】:Gorm Many-to-one foreign key on only one modelGorm 仅在一个模型上的多对一外键
【发布时间】:2020-09-26 12:15:39
【问题描述】:

在 golang 中使用 gorm,我有 2 个模型:Shipment 和 Customer

基本上在 Shipment 模型上,我有一个对应于客户 ID 的 int。 但是在客户方面,我没有将其与 Shipments 链接的字段。

这是我的模型:

type Shipment struct {
    ID                                      int64         `json:"id"`
    Customer                                Customer      `json:"customer"`
} 

type Customer struct {
    ID                                  int64       `json:"id"`
    Name                                string      `json:"name"`
} 

在数据库中,我有:

map_shipment (table name)
id, customer_id
map_customer (table name)
id, name

这是我当前使用的请求。

db.Table("map_shipment").Preload(clause.Associations).Find(&shipments)

如何防止 gorm 在 Customer 上查找 ShipmentId 字段?

【问题讨论】:

    标签: sql postgresql go go-gorm


    【解决方案1】:

    我只需在 Shipment 模型中添加 CustomerID int 即可使其正常工作。

    所以发货模式是:

    type Shipment struct {
        ID                                      int64         `json:"id"`
        CustomerID                              int64         `json:"customer_id"`
        Customer                                Customer      `json:"customer"`
    } 
    

    无需在 Customer 模型中添加任何 Shipment 或 []Shipment 的引用

    【讨论】:

      猜你喜欢
      • 2021-10-13
      • 1970-01-01
      • 2016-03-13
      • 2017-06-01
      • 2023-02-08
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      相关资源
      最近更新 更多