当我尝试预加载时,如文档中所述,我会收到错误Cameras:schema RecordingServer不支持的关系
我也在取消对模式的签名以进行json验证,不想使用Gorm模型,也不想使用类型为uuid的Guid作为主键。我无法独自解决这个问题,所以如果有任何帮助,我们将不胜感激。当然,我读过其他帖子,但没有找到合适的解决方案。
var rs []sdk.RecordingServer
err := database.Session.Preload("Cameras").Find(&rs)
fmt.Println(err, rs)
// Cameras: unsupported relations for schema RecordingServer
# Models
type RecordingServerBase struct {
Name string `json:"name" gorm:"size:128"`
Address string `json:"address" gorm:"size:16"`
Cameras []Camera `json:"cameras" gorm:"foreignKey:RecordingServerGuid;type:uuid"`
}
type RecordingServer struct {
Guid uuid.UUID `json:"guid" format:"uuid" gorm:"type:uuid;primaryKey";`
RecordingServerBase
}
type CameraBase struct {
Name string `json:"name" gorm:"size:128"`
Address string `json:"address" gorm:"size:16"`
Username string `json:"username" gorm:"size:32"`
Password string `json:"password" gorm:"size:64"`
RecordingServerGuid uuid.UUID
}
type Camera struct {
Guid uuid.UUID `json:"guid" format:"uuid" gorm:"type:uuid;primaryKey";`
CameraBase
}
当我只做一个简单的sql时,它可以与一起工作
SELECT * FROM `cameras` WHERE recording_server_guid IN ('55c0b198-9ec3-4270-8030-77546ab40c19');
感谢
您应该将type:uuid
放在字段定义中,而不是放在关系中。
如果我将其自动迁移到db:,这将起作用
type RecordingServerBase struct {
Name string `json:"name" gorm:"size:128"`
Address string `json:"address" gorm:"size:16"`
Cameras []Camera `json:"cameras" gorm:"foreignKey:RecordingServerGuid"`
}
type RecordingServer struct {
Guid uuid.UUID `json:"guid" format:"uuid" gorm:"type:uuid;primaryKey"`
RecordingServerBase
}
type CameraBase struct {
Name string `json:"name" gorm:"size:128"`
Address string `json:"address" gorm:"size:16"`
Username string `json:"username" gorm:"size:32"`
Password string `json:"password" gorm:"size:64"`
RecordingServerGuid uuid.UUID `gorm:"type:uuid"`
}
type Camera struct {
Guid uuid.UUID `json:"guid" format:"uuid" gorm:"type:uuid;primaryKey"`
CameraBase
}
请注意,Find()
不会返回错误。您可能想要使用:
err := db.Find(&rs).Error