Adrien Chapelet
Adrien Chapelet

Reputation: 450

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

Using gorm in golang, I have 2 models: Shipment and Customer

Basically on Shipment model, I have an int that corresponds to a customer id. But on customer, I have no field to link it with Shipments.

Here are my models:

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

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

In database, I have:

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

Here is the request I am currently using.

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

How can I prevent gorm to look for a ShipmentId field on Customer?

Upvotes: 0

Views: 1154

Answers (1)

Adrien Chapelet
Adrien Chapelet

Reputation: 450

I had just to add the CustomerID int in the Shipment model to make it working.

So the shipment model is:

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

No need to add any reference of Shipment or []Shipment in Customer model

Upvotes: 1

Related Questions