Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

many2many has a question:Error 1075: Incorrect table definition; there can be only one auto column and it must be defined as a key #5476

Closed
fivenull opened this issue Jul 1, 2022 · 2 comments
Assignees
Labels
type:question general questions

Comments

@fivenull
Copy link

fivenull commented Jul 1, 2022

Description

多对多关联,表迁移的时候,如果中间表对应的关联表不是主键id的话,创建会报错,报错内容为:

Error 1075: Incorrect table definition; there can be only one auto column and it must be defined as a key

例子:

type Area struct{
        ID        uint           `gorm:"primarykey"` // 主键ID
        Code     int           `json:"code" form:"code" gorm:"column:code;type:int"`
	Schools []School  `json:"schools" gorm:"many2many:school_areas;foreignKey:Code;joinForeignKey:area_id;references:ID;JoinReferences:school_system_id"`
}

type School struct{
        ID        uint           `gorm:"primarykey"` // 主键ID
        Areas []AreaModel `json:"areas" gorm:"many2many:school_areas;foreignKey:ID;joinForeignKey:school_system_id;references:Code;JoinReferences:area_id"`
}

其中中间表为school_areas
2个主表

主表schools 的主键id字段,对应中间表的school_system_id字段
主表areas 的code字段,对应中间表的area_id字段

自动迁移的时候就会报错,生成的sql为

CREATE TABLE `school_areas` (`area_id` bigint COMMENT '省市编码',`school_system_id` bigint unsigned AUTO_INCREMENT,PRIMARY KEY (`area_id`,`school_system_id`))

数据库运行报1075错误,数据库版本为 5.7+
go版本为 1.16
gorm版本为 v1.21.12

@github-actions github-actions bot added the type:question general questions label Jul 1, 2022
@fivenull
Copy link
Author

fivenull commented Jul 1, 2022

schools表和areas表主键都需要设置自增

@a631807682
Copy link
Member

duplicated of #5320
upgrade gorm version

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type:question general questions
Projects
None yet
Development

No branches or pull requests

3 participants