【问题标题】:Gorm call Where() with foreignkeyGorm 使用外键调用 Where()
【发布时间】:2020-11-11 15:34:41
【问题描述】:

我有一个 gorm 模型:

type Order struct {
    ID             int    `json:"id" gorm:"column:id"`
    ProductID      int    `json:"product_id" gorm:"column:product_id"`
    Price int    `json:"per_credit_price" gorm:"column:per_credit_price"`

    Product Product `gorm:"foreignkey:ProductID;AssociationForeignKey:ID"`
}

我想写一个查询,比如:

p.DB.Preload("Product").Where(ord).First(ord).Error

如果我的 ord 结构包含 Product 作为结构,它会返回以下错误:

sql:转换参数 $8 类型:不支持的类型 models.Product,a 结构体

它可以找到 Find() 而不是 Where(),但我想查询 ID 以外的其他内容。

我怎样才能让它工作?

【问题讨论】:

  • 只在不需要传递完整结构数据的地方传递id

标签: sql go go-gorm


【解决方案1】:

使用结构体的指针进行查找

var ord Order 
p.DB.Preload("Product").Where(ord).First(&ord).Error

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 2021-05-18
    • 1970-01-01
    相关资源
    最近更新 更多