入れ子になったリレーションシップを STI 構造体にプリロードすると、奇妙な SQL が発生します。
会社の構造:
type Firm struct {
gorm.Model
FirmIdentifier string
Name string
Type string
ClearingMember *Firm `gorm:"ForeignKey:ClearingMemberID"`
ClearingMemberID int
ExecutingFirm *Firm `gorm:"ForeignKey:ExecutingFirmID"`
ExecutingFirmID int
Address Address `gorm:"polymorphic:Addressable;"`
Contacts []Contact
}
type Execution struct {
ID uint
Price int
Side string
Symbol string
ExecutingFirm Firm `gorm:"ForeignKey:FirmID"`
FirmID int
}
実際のデータは次のとおりです。
-
id: 1
name: Clearing Member 1
type: ClearingMember
clearing_member_id:
-
id: 3
name: Executing Firm 1
type: ExecutingFirm
clearing_member_id: 1
-
# Execution
id: 1
side: SELL
price: 1000
symbol: FUT.EXC.201612
firm_id: 3
このクエリ:
db.Preload("ExecutingFirm").Preload("ExecutingFirm.ClearingMember").Find(&executions)
clearing_member_id
ID が 1 の会社ではなく、3の会社を検索する以下の SQL を生成します。
(/home/vagrant/go/src/message_builder_test.go:90)
[2016-09-15 18:30:33] [1.14ms] SELECT * FROM `executions`
(/home/vagrant/go/src/message_builder_test.go:90)
[2016-09-15 18:30:33] [1.51ms] SELECT * FROM `firms` WHERE `firms`.deleted_at IS NULL AND ((`id` IN ('3','4')))
(/home/vagrant/go/src/message_builder_test.go:90)
[2016-09-15 18:30:33] [1.24ms] SELECT * FROM `firms` WHERE `firms`.deleted_at IS NULL AND ((`clearing_member_id` IN ('3','4')))