Many2Many on existing db entities empty
The database and the table exist. Migrations and management remain in the third-party application. I migrate the structure using a script. Django application, if this is important.
Structs:
type DatahubMnemoEquipment struct {
ID int64 `gorm:"primaryKey" gorm:"column:id"`
Works []*DatahubDeviceParameter `gorm:"many2many:datahub_mnemoequipment_works;joinForeignKey:MnemoequipmentID;"`
}
func (DatahubMnemoEquipment) TableName() string {
return "datahub_mnemoequipment"
}
type DatahubDeviceParameter struct {
ID int64 `gorm:"primaryKey" gorm:"column:id"`
Tag string `gorm:"column:tag"`
}
func (DatahubDeviceParameter) TableName() string {
return "datahub_deviceparameter"
}
type DatahubMnemoequipmentWorks struct {
ID int64 `gorm:"primaryKey" gorm:"column:id"`
MnemoequipmentID int64 `gorm:"column:mnemoequipment_id"`
Mnemoequipment *DatahubMnemoEquipment
DeviceparameterID int64 `gorm:"column:deviceparameter_id"`
Deviceparameter *DatahubDeviceParameter
}
func (DatahubMnemoequipmentWorks) TableName() string {
return "datahub_mnemoequipment_works"
}
Query:
var equipments []db_models.DatahubMnemoEquipment
conn.Debug().Preload("Works").Preload(clause.Associations).Where("source_id = ?", source.Item.ID).Find(&equipments)
or simple
conn.Debug().Preload(clause.Associations).Where("source_id = ?", source.Item.ID).Find(&equipments)
Logs:
[30.720ms] [rows:20] SELECT * FROM "datahub_mnemoequipment_works" WHERE "datahub_mnemoequipment_works"."mnemoequipment_id" IN (60277,60278,60279,60280,60289,60281,60282)
[346.825ms] [rows:100] SELECT * FROM "datahub_mnemoequipment" WHERE source_id = 'BLU_4'
Debug:
With any tag configuration, the value is either nil or as in the picture above.
The document you expected this should be explained
https://gorm.io/docs/many_to_many.html
Expected answer
What am I doing wrong and a more detailed description or example with foreignKey, references, joinForeignKey, joinReferences
Comment From: github-actions[bot]
This issue has been automatically marked as stale because it has been open 360 days with no activity. Remove stale label or comment or this will be closed in 180 days