我有以下struct
:
type Relation struct {
Metric *Metric `gorm:"foreignkey:MetricID"`
MetricID uint
...
}
Metric
定义为:
type DatabaseMeta struct {
Id uint `json:"-" gorm:"primary_key"`
}
type Metric struct {
DatabaseMeta
Name string `json:"name"`
Medium string `json:"medium"`
}
我希望使用GORM从Relation
中的值集中找到Metric
,它具有FK关联。
我试过了:
var relation common.Relation
database.Preload("Relation.Metric").Where(&Relation{
Metric: &Metric{
Name: "temperature",
Medium: "water",
},
}).First(&relation)
尽管Preload
并尝试Association
和Preload
个参数的组合,但以下SQL实际上是由GORM生成的:
[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 ]
这在概念上符合我的要求:
// 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)
如何使用GORM通过其外键关系中设置的字段来查找struct
?这可能吗?