【发布时间】:2021-05-18 01:15:39
【问题描述】:
我定义了两个数据库结构
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 instead
IN 查询使用Main 结构的主键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
参考资料:
【问题讨论】: