doushang1890 2018-10-16 07:48
浏览 48
已采纳

在关联表中插入时创建关联问题

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

}

I am trying to insert a record like this

newGroup: = &Group{
            CreatedBy: newGroupDetails.UserID,
            GroupOrders: []GroupOrder{
                {
                    OrderID:     newGroupDetails.OrderID,
                    UserID:      newGroupDetails.UserID,
                },
            },
        }

I am creating a record by using this.

db.Create(newGroup)

It creates a record correctly in Group model but while inserting in GroupOrder model, it is inserting NULL value in group_id column.

After that, it fires a query

INSERT INTO group_orders (group_id) SELECT ? FROM DUAL WHERE NOT EXISTS (SELECT * FROM group_orders WHERE group_id = ?)[30 30] 1  pkg=mysql

And then insert another record in GroupOrder Model with all empty fields but adding the group id field as the previously inserted group_order_id value.

The resultant data in mysql

GroupOrder

    | id | group_id | order_id | user_id |
    +----+---------------+----------+---------+
    | 30 |             0 |  8764822 |  678972 |
    | 31 |            30 |     NULL |    NULL |

Group

    | id | created_by |
    +----+------------+
    | 18 |     678972 |

At least, it should be inserting 18 in place of 30 in the last row group_id column in GroupOrder table.

Why is this happening? Can someone explain if there's a bug.

PS: For brevity, removed a few other columns from both Models.

  • 写回答

1条回答 默认 最新

  • duangang1991 2018-10-16 09:41
    关注

    Found the bug myself. Group has an has-many association with GroupOrder and not many to many. Removed that and it worked clean.

    Hope it helps someone :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题