users使用gorm,我为和product_prices表创建了以下模型// model for table `users`type User struct { Id uint64 `json:"id" gorm:"primaryKey"` Email string `json:"email" gorm:"unique"` Password []byte `json:"-"` CreatedOn time.Time `json:"created_on" gorm:"<-:create"` UpdatedOn time.Time `json:"updated_on"`}// model for table `product_prices`type ProductPrice struct { Id uint64 `json:"id" gorm:"primaryKey"` Price float64 `json:"price"` Direction string `json:"direction"` NotificationMethod string `json:"notification_method"` CreatedOn time.Time `json:"created_on,omitempty" gorm:"<-:create"` UpdatedOn time.Time `json:"updated_on,omitempty"` LastNotified time.Time `json:"last_notified,omitempty"` UserId uint64 `json:"user_id"` User User `json:"-" gorm:"foreignKey:UserId"`}我想做一些类似在product_prices和users表之间执行以下sql连接的事情select product_prices.id, product_prices.price, product_prices.created_on, users.email as user_email, users.created_on as user_created_on from product_prices join users on product_prices.user_id=users.id;这是我尝试过但仍然不走运的许多事情之一,这要归功于文档页面https://gorm.io/docs/query.html#Joins不够清晰, 我还想遍历行按照这里的文档https://gorm.io/docs/query.html#Joins我尝试了以下// struct for result of join querytype ProductPriceUser struct { Id uint64 `json:"id"` Price float64 `json:"price"` CreatedOn time.Time `json:"created_on,omitempty"` UserEmail User `json:"user_email"` UserCreatedOn User `json:"user_created_on"`}但是我遇到了各种各样的错误,我做错了什么,我如何得到我想要的,如上所述?谢谢!
1 回答
茅侃侃
TA贡献1842条经验 获得超21个赞
一种可能的解决方案是做这样的事情(假设你的数据库表被命名为product_pricesand users):
list := []ProductPriceUser{}
err := database.DB.Table("product_prices").
Join("JOIN users ON users.id=product_prices.user_id").
Select("product_prices.id, product_prices.price, product_prices.created_on, users.email as user_email, users.created_on as user_created_on").
Find(&list).Error
if err != nil {
// handle error
}
然后,您可以遍历list以获取每条记录。
- 1 回答
- 0 关注
- 172 浏览
添加回答
举报
0/150
提交
取消