Mysql 覆盖gorm中的外键和引用

Mysql 覆盖gorm中的外键和引用,mysql,go,go-gorm,Mysql,Go,Go Gorm,我定义了两个DB结构 类型主结构{ 戈姆模型 GroupID int64`gorm:column:group\u id` GroupName字符串`gorm:column:group\u name` ItemID字符串`gorm:列:item\u id` Item Item`gorm:foreignKey:ItemID;references:Item\u id` } 类型项结构{ 戈姆模型 ItemID字符串`gorm:列:item\u id` ItemName字符串`gorm:columnit

我定义了两个DB结构

类型主结构{ 戈姆模型 GroupID int64`gorm:column:group\u id` GroupName字符串`gorm:column:group\u name` ItemID字符串`gorm:列:item\u id` Item Item`gorm:foreignKey:ItemID;references:Item\u id` } 类型项结构{ 戈姆模型 ItemID字符串`gorm:列:item\u id` ItemName字符串`gorm:columnitem\u名称` } 但是,当我进行选择时,即

干线:=制造[]*干线,0 db.WheresomeFilters.preloitem.Find&mains 我收到了询问

从主电源中选择*,其中条件1='condition_value'; 从第1、2项中包含项目id的项目中选择*;改为使用Main的ID字段作为参数 IN查询使用主结构的主键id而不是字段项\ id。我在这里做错了什么吗?我只想通过item_id获得连接的结果,也就是说,我希望第二个查询是

从“主项目1”项目id、“主项目2”项目id“中的项目id中选择*; 更新:还尝试将标记更改为关联\外部\密钥

类型主结构{ 戈姆模型 GroupID int64`gorm:column:group\u id` GroupName字符串`gorm:column:group\u name` ItemID字符串`gorm:列:item\u id` Item Item`gorm:association\u foreignkey:ItemID;references:Item\u id` } 现在生成的SQL是

从主电源中选择*,其中条件1='condition_value'; 从'main_1_item_id'、'main_2_item_id'中id所在的项目中选择*;使用Main的ItemID字段,但使用Item的ID字段作为查询 参考资料:


[1]

我有几个想法,你可能想研究一下:

第一:既然在主结构中有一个Item结构,为什么要为ItemID使用第二个字段,因为Item结构中已经有一个字段了。Gorm非常擅长自动处理关联,请尝试简单地将项结构嵌入到主结构中


第二:当您嵌入gorm.Model时,它将其Id字段声明为结构的主键,这也可能会导致问题。

我有一些想法,您可能需要研究一下:

第一:既然在主结构中有一个Item结构,为什么要为ItemID使用第二个字段,因为Item结构中已经有一个字段了。Gorm非常擅长自动处理关联,请尝试简单地将项结构嵌入到主结构中


第二:当嵌入gorm.Model时,它将其Id字段声明为结构的主键,这也可能导致问题。

我找到了解决问题的方法

gorm标签应该是

类型主结构{ 戈姆模型 GroupID int64`gorm:column:group\u id` GroupName字符串`gorm:column:group\u name` ItemID字符串`gorm:列:item\u id` Item Item`gorm:associationForeignKey:ItemID;foreignKey:ItemID` } 类型项结构{ 戈姆模型 ItemID字符串`gorm:列:item\u id` ItemName字符串`gorm:columnitem\u名称` } 现在,生成的SQL查询是

从主电源中选择*,其中条件1='condition_value'; 从“主项目1”项目id、“主项目2”项目id“中的项目id中选择*;
我找到了解决我问题的办法

gorm标签应该是

类型主结构{ 戈姆模型 GroupID int64`gorm:column:group\u id` GroupName字符串`gorm:column:group\u name` ItemID字符串`gorm:列:item\u id` Item Item`gorm:associationForeignKey:ItemID;foreignKey:ItemID` } 类型项结构{ 戈姆模型 ItemID字符串`gorm:列:item\u id` ItemName字符串`gorm:columnitem\u名称` } 现在,生成的SQL查询是

从主电源中选择*,其中条件1='condition_value'; 从“主项目1”项目id、“主项目2”项目id“中的项目id中选择*;