繁体   English   中英

我可以使用 preload 在 gorm 中加载三个表吗?

[英]Can I use preload to load three table in gorm?

我有下面三个表:

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
}

我可以预加载以加载 1 个用户的所有产品 - 使用预加载的平均状态为 1(因为从设备到用户没有外键)?

是的,您可以参考文档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

或预加载所有

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM