我正在将GORM与PostgreSQL数据库一起使用。我有一个预先存在的迁移的地方(不使用gorm来处理迁移)。我有2个相互关联的结构,代表2个表,这些表在所述数据库中有很多关系。
迁移:
CREATE TABLE IF NOT EXISTS items_captions (
id varchar(50) NOT NULL,
item_id varchar(50) NOT NULL REFERENCES items(item_id) ON DELETE CASCADE,
source varchar(50) NOT NULL,
filepath varchar(256) NOT NULL,
language varchar(50),
language_confidence decimal,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
PRIMARY KEY(id)
);
CREATE TABLE IF NOT EXISTS captions (
id varchar(50) NOT NULL,
item_captions_id varchar(50) NOT NULL REFERENCES items_captions(id) ON DELETE CASCADE,
start_at DECIMAL NOT NULL,
end_at DECIMAL NOT NULL,
"text" TEXT NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
PRIMARY KEY(id)
);
结构定义:
type ItemsCaptions struct {
ID string `gorm:"id"`
ItemID string `gorm:"item_id"`
Source string `gorm:"source"`
Filepath string `gorm:"filepath"`
Language string `gorm:"language"`
LanguageConfidence float64 `gorm:"language_confidence"`
CreatedAt time.Time `gorm:"created_at"`
UpdatedAt time.Time `gorm:"updated_at"`
Captions []Caption `gorm:"foreignkey:ItemCaptionsID"`
}
type Caption struct {
ID string `gorm:"id"`
ItemCaptionsID string `gorm:"item_captions_id"`
StartAt float64 `gorm:"start_at"`
EndAt float64 `gorm:"end_at"`
Text string `gorm:"text"`
CreatedAt time.Time `gorm:"created_at"`
UpdatedAt time.Time `gorm:"updated_at"`
}
问题: 在执行插入时,数据似乎已正确插入。尝试从数据库中查询出数据时会出现问题。
var itemCaptions []ItemsCaptions
db.Find(&itemCaptions).Error
var captions []Caption
db.Model(&itemCaptions[0]).Related(&captions)
// no items from db are returned
// However querying the database directly shows that the data was inserted as expected.
此外,我从gorm invalid association []
的日志中收到以下消息
其他信息: 我试图在db.Debug()中运行相同的东西,但没有产生任何其他信息。
很明显,我做错了什么,但是我不清楚这是什么。请让我知道是否需要更多信息。