type Group struct { gorm.Model CreatedBy uint64 GroupOrders []GroupOrder gorm:"many2many:group_orders;association_jointable_foreignkey:group_id;jointable_foreignkey:group_id;" } type GroupOrder struct { gorm.Model GroupID uint64 OrderID uint64 UserID uint64 Group Group}我正在嘗試插入這樣的記錄newGroup: = &Group{ CreatedBy: newGroupDetails.UserID, GroupOrders: []GroupOrder{ { OrderID: newGroupDetails.OrderID, UserID: newGroupDetails.UserID, }, }, }我正在使用它創(chuàng)建記錄。db.Create(newGroup)它在 Group 模型中正確創(chuàng)建記錄,但在 GroupOrder 模型中插入時,它在 group_id 列中插入 NULL 值。之后,它會觸發(fā)一個查詢INSERT INTO group_orders (group_id) SELECT ? FROM DUAL WHERE NOT EXISTS (SELECT * FROM group_orders WHERE group_id = ?)[30 30] 1 pkg=mysql然后在 GroupOrder 模型中插入另一條記錄,所有字段均為空,但將組 ID 字段添加為先前插入的 group_order_id 值。mysql中的結果數(shù)據(jù)團購 | id | group_id | order_id | user_id | +----+---------------+----------+---------+ | 30 | 0 | 8764822 | 678972 | | 31 | 30 | NULL | NULL |團體 | id | created_by | +----+------------+ | 18 | 678972 |至少,它應該在 GroupOrder 表的最后一行 group_id 列中插入 18 代替 30。為什么會這樣?有人可以解釋一下是否有錯誤。PS:為簡潔起見,從兩個模型中刪除了一些其他列。
1 回答

肥皂起泡泡
TA貢獻1829條經(jīng)驗 獲得超6個贊
自己發(fā)現(xiàn)了錯誤。Group 與 GroupOrder 具有多對多關聯(lián)。刪除它并且它工作干凈。
希望它能幫助別人:)
- 1 回答
- 0 關注
- 152 瀏覽
添加回答
舉報
0/150
提交
取消