I have the following struct
:
type Relation struct {
Metric *Metric `gorm:"foreignkey:MetricID"`
MetricID uint
...
}
Metric
is defined as:
type DatabaseMeta struct {
Id uint `json:"-" gorm:"primary_key"`
}
type Metric struct {
DatabaseMeta
Name string `json:"name"`
Medium string `json:"medium"`
}
I'd like to find a Relation
from a value set in Metric
using GORM, which has a FK association.
I tried:
var relation common.Relation
database.Preload("Relation.Metric").Where(&Relation{
Metric: &Metric{
Name: "temperature",
Medium: "water",
},
}).First(&relation)
Despite Preload
and trying combinations of Association
and Preload
arguments, the following SQL is actually generated by 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 ]
This works and is conceptually what I'm looking for:
// 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)
How can I use GORM to find a struct
by a field set in its foreign key relation? Is this possible?