簡體   English   中英

Gorm 多對一外鍵僅用於一種模型

[英]Gorm Many-to-one foreign key on only one model

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

基本上在 Shipment 模型上,我有一個對應於客戶 ID 的 int。 但是對於客戶,我沒有將其與發貨鏈接的字段。

這是我的模型:

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 的任何引用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM