【问题标题】:How do I Perform Join With GORM and iterate over rows of result?如何使用 GORM 执行联接并遍历结果行?
【发布时间】:2022-01-27 21:28:52
【问题描述】:

使用 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")
}

但是我得到了各种各样的错误,我做错了什么,我如何得到我想要的如上所述?

谢谢!

【问题讨论】:

    标签: sql postgresql go join go-gorm


    【解决方案1】:

    一种可能的解决方案是这样做(假设您的数据库表名为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 以获取每条记录。

    【讨论】:

      猜你喜欢
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 2022-01-18
      相关资源
      最近更新 更多