登录
首页 >  Golang >  Go问答

在插入时建立关联的表格操作

来源:stackoverflow

时间:2024-03-23 08:12:32 334浏览 收藏

在建立关联的表格操作中,插入数据时出现了异常行为。在插入 GroupOrder 表格时,GroupOrder 的 group_id 列中被错误地插入了 null 值,导致查询触发并插入了另一条记录,该记录中所有字段为空,但添加了错误的 group_id 值。分析发现,导致问题的根源在于模型中错误地将 Group 与 GroupOrder 定义为多对多关联关系,而不是多对一关联关系。

问题内容

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,
                },
            },
        }

我正在使用它创建一条记录。

db.create(newgroup)

它在 group 模型中正确创建了一条记录,但在 grouporder 模型中插入时,它在 group_id 列中插入 null 值。

之后,它会触发一个查询

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中的结果数据

组订单

| 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:为了简洁起见,从两个模型中删除了一些其他列。


解决方案


我自己发现了这个错误。 Group 与 GroupOrder 具有多对关联关系,但不是多对多关联。删除它,它就干净了。

希望它能帮助别人:)

今天关于《在插入时建立关联的表格操作》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>