只有一个模型的 Gorm 多对一外键

Gorm Many-to-one foreign key on only one model

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

基本上在 Shipment 模型上,我有一个对应于客户 ID 的整数。 但是在客户方面,我没有 link 与 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 字段?

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

所以发货型号为:

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

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