我定义了两个DB结构
type Main struct {
gorm.Model
GroupID int64 `gorm:"column:group_id"`
GroupName string `gorm:"column:group_name"`
ItemID string `gorm:"column:item_id"`
Item Item `gorm:"foreignKey:ItemID;references:item_id"`
}
type Item struct {
gorm.Model
ItemID string `gorm:"column:item_id"`
ItemName string `gorm:"column"item_name"`
}但是,当我做一个选择时,即
mains := make([]*Main, 0)
db.Where(someFilters).Preload("Item").Find(&mains)我收到问询
SELECT * FROM mains WHERE condition1='condition_value';
SELECT * FROM items WHERE item_id IN (1, 2); # Uses Main's ID field as the argument insteadIN查询使用Main结构的主键item_id,而不是使用字段item_id。我在这里做错什么了吗?我只想通过item_id获得“连接”结果,也就是说,我希望第二个查询是
SELECT * FROM items WHERE item_id IN (`main_1_item_id`, `main_2_item_id`);更新:还尝试将标记更改为association_foreign_key
type Main struct {
gorm.Model
GroupID int64 `gorm:"column:group_id"`
GroupName string `gorm:"column:group_name"`
ItemID string `gorm:"column:item_id"`
Item Item `gorm:"association_foreignkey:ItemID;references:item_id"`
}现在生成的SQL是
SELECT * FROM mains WHERE condition1='condition_value';
SELECT * FROM items WHERE id IN (`main_1_item_id`, `main_2_item_id`); # Uses Main's ItemID field but using Item's ID field as query参考资料:
发布于 2021-02-15 06:49:44
我已经找到了解决问题的办法。
gorm标记应该是
type Main struct {
gorm.Model
GroupID int64 `gorm:"column:group_id"`
GroupName string `gorm:"column:group_name"`
ItemID string `gorm:"column:item_id"`
Item Item `gorm:"associationForeignKey:ItemID;foreignKey:ItemID"`
}
type Item struct {
gorm.Model
ItemID string `gorm:"column:item_id"`
ItemName string `gorm:"column"item_name"`
}现在生成的SQL查询是
SELECT * FROM mains WHERE condition1='condition_value';
SELECT * FROM items WHERE item_id IN (`main_1_item_id`, `main_2_item_id`);发布于 2021-02-15 06:42:23
我有几个想法你可能想研究一下:
第一:既然在Item结构中有一个Main结构,为什么要为ItemID使用第二个字段,那么项结构中已经有一个字段了。Gorm非常擅长自动处理关联,只需将Item结构嵌入到Main结构中即可。
第二:当嵌入gorm.Model时,它将其Id字段声明为结构的主键,这也可能导致问题。
https://stackoverflow.com/questions/66203163
复制相似问题