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

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.

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 :)