Can I use preload to load three table in gorm?

Viewed 35

I have three table below:

type struct Product {
      Id  int 
      Name string
}
type struct Order {
      Id int
      Name string
      Status int //0-not use 1 - use
      UserId int    'foreginKey:UserId'
      ProductId int 'foreignKey:ProductId, reference:Id'
}
type struct User {
      Id int       
      Name int
}

Can I you preload from to load all product of 1 user - mean status is 1 using preload (because no foregin key from device to user)?

1 Answers

Yes you can refer to the docs https://gorm.io/docs/preload.html

db.Preload("Orders").Preload("Profile").Preload("Role").Find(&users)
// SELECT * FROM users;
// SELECT * FROM orders WHERE user_id IN (1,2,3,4); // has many
// SELECT * FROM profiles WHERE user_id IN (1,2,3,4); // has one
// SELECT * FROM roles WHERE id IN (4,5,6); // belongs to

or preload all

db.Preload(clause.Associations).Find(&users)
Related