GORM Playground Link

https://github.com/go-gorm/playground/pull/615

Description

所有的信息都在上面的那个pr中,其中最主要的就是以下代码:

func TestGORM(t *testing.T) {
    // user := User{Name: "jinzhu"}
    // 使用many2many创建关联表后,又再次AutoMigrate创建关联表,因为之前创建了联合索引(primary key (user_id, friend_id)),导致关系表无法增加新的主键索引(id).
    // 当项目复杂,涉及很多表时,研发人员不容易关注到这个问题。
    // 期望的解决方案:默认应该设置IgnoreRelationshipsWhenMigrating=true,来规避此问题?
    err := DB.AutoMigrate(&User{}, &UserFriend{})
    failOnError(t, err)
}

playground的测试输出如下

2023/06/08 10:00:34 /home/runner/work/playground/playground/main_test.go:16 Error 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key
[0.512ms] [rows:0] ALTER TABLE `user_friends` ADD `id` bigint unsigned AUTO_INCREMENT
    main_test.go:17: Error 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key
--- FAIL: TestGORM (0.03s)
FAIL
FAIL    gorm.io/playground  0.216s
FAIL
Error: Process completed with exit code 1.

当开发者对gorm的AutoMigrate和many2many标记了了解不深入时,很容易像我上面那样使用AutoMigrate。 当gorm使用默认配置时(IgnoreRelationshipsWhenMigrating=false),开发者可能容易忽略many2many会创建关联表,同时还会给表创建唯一的联合搜索。 通过many2many产生的关系表就无法新增加一个id主键搜索了。 这使得AutoMigrate和many2many功能叠加起来时,容易产生问题。

你觉得应该如何改进这个问题?