如何使用 GORM 执行连接并遍历结果行?

How do I Perform Join With GORM and iterate over rows of result?

使用 gorm,我为 usersproduct_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_pricesusers 表之间执行以下 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 query
type 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"`
}

var productPrice ProductPrice

database.DB.Model(&productPrice{}).Select("productPrices.id, productPrices.price, productPrices.created_on, users.email as users_email, users.created_on as users_created_on").Joins("join user on productPrices.user_id = users.id").Scan(&ProductPriceUser{})

for _, row := range ProductPriceUser {
    fmt.Println("values: ", row.Id, row.Price, row.CreatedOn, row.UserEmail, row.UserCreatedOn, "\n")
}

但是我遇到了各种各样的错误,我做错了什么以及我如何得到上面描述的我想要的东西?

谢谢!

一个可能的解决方案是做这样的事情(假设你的数据库表被命名为 product_pricesusers):

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 以获取每条记录。