我有以下内容struct:
type Relation struct {
Metric *Metric `gorm:"foreignkey:MetricID"`
MetricID uint
...
}
Run Code Online (Sandbox Code Playgroud)
Metric定义为:
type DatabaseMeta struct {
Id uint `json:"-" gorm:"primary_key"`
}
type Metric struct {
DatabaseMeta
Name string `json:"name"`
Medium string `json:"medium"`
}
Run Code Online (Sandbox Code Playgroud)
我想Relation从使用 GORM 中设置的值中找到 a Metric,它具有 FK 关联。
我试过:
var relation common.Relation
database.Preload("Relation.Metric").Where(&Relation{
Metric: &Metric{
Name: "temperature",
Medium: "water",
},
}).First(&relation)
Run Code Online (Sandbox Code Playgroud)
尽管尝试了和参数Preload的组合,以下 SQL 实际上是由 GORM 生成的:AssociationPreload
[2018-05-06 18:47:37] sql: converting argument $1 type: unsupported type common.Metric, a struct
[2018-05-06 18:47:37] [0.14ms] SELECT * FROM "relations" WHERE ("relations"."metric" = '{{0} temperature water}') LIMIT 1
[0 rows affected or returned ]
Run Code Online (Sandbox Code Playgroud)
这有效并且从概念上讲就是我正在寻找的:
// Look up the metric from `Name` and `Medium` fields
var metric Metric
database.Where(&Metric{
Name: "temperature",
Medium: "water",
}).First(&metric)
// Use the `metric` FK directly to search for the `relation`
var relation Relation
database.Where(&Relation{
MetricID: metric.DatabaseMeta.Id,
}).First(&relation)
Run Code Online (Sandbox Code Playgroud)
如何使用 GORMstruct通过外键关系中设置的字段来查找?这可能吗?
| 归档时间: |
|
| 查看次数: |
1082 次 |
| 最近记录: |