在 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 字段?
最佳答案
我只需在 Shipment 模型中添加 CustomerID int 即可使其正常工作。
所以出货模型为:
type Shipment struct {
ID int64 `json:"id"`
CustomerID int64 `json:"customer_id"`
Customer Customer `json:"customer"`
}
无需在 Customer 模型中添加任何 Shipment 或 []Shipment 的引用
关于sql - Gorm 仅在一个模型上的多对一外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64077570/