sql - Gorm 仅在一个模型上的多对一外键

标签 sql postgresql go go-gorm

在 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/

相关文章:

sql - 数据源和数据集的区别

spring - 如何使用 Spring 在启动时加载 sql 函数?

linux - postgresql 不随 Linux 启动

戈朗 : goroutine infinite-loop

generics - 为什么 Go 中没有泛型?

golang 中的 json 编码数组列表

sql - 查询返回笛卡尔积 (Northwind)

php - 出现 MySQL 错误 "unknown column"但该列存在

mysql - 如果特定列同时具有两个值,如何从数据库中获取 ID

java - 使用 Java 调用 PostgreSQL 存储过程返回 null